简体   繁体   中英

Null Reference Exception when i use navigation property in model class

I try to add new entity in database in controller action.
This is my model class

    public class Product
    {
    public int ProductID { get; set; }

    [Required(ErrorMessage = "Please enter product name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please enter product model")]
    public string Model { get; set; }

    [Required(ErrorMessage = "Please enter product serial")]
    public string Serial { get; set; }

    [Required(ErrorMessage = "Please choose dealer")]      
    public int DealerID { get; set; }

    [Required]        
    public Guid ClientID { get; set; }

    [Required(ErrorMessage = "Please choose employee")]
    public Guid EmployeeID { get; set; }

    public virtual Dealer Dealer { get; set; }
    public virtual Client Client { get; set; }
    public virtual Employee Employee { get; set; }

    [DisplayName("Commercial use")]
    public bool UseType { get; set; }
}

This is actions for creating new product in database

    public ViewResult Create()
    {
        PopulateDropDownLists();
        var model = new Product();
        return View(model);
    }

    [HttpPost]
    public ActionResult Create(Product model)
    {
        try
        {
            if (ModelState.IsValid)
            {
                _repo.GetRepository<Product>().Add(model);
                _repo.Save();
                TempData["message"] = "Product was successfully created";
                return RedirectToAction("List");
            }
        }
        catch (DataException)
        {
            TempData["error"] =
                "Unable to save changes. Try again, and if the problem persists, see your system administrator.";
            return View("Error");
        }

        PopulateDropDownLists();
        return View("Create");
    }

CreateView has appropriate model type (Product type in this case). Code below

    @using System.Web.Mvc.Html
    @model STIHL.WebUI.Models.Product

    @using (Html.BeginForm())
    {
       @Html.EditorFor(m => m.Name)
       @Html.EditorFor(m => m.Model)
       @Html.EditorFor(m => m.Serial)

    <div class="form-group">
        @Html.LabelFor(m => m.DealerID, "Dealer")
        @Html.DropDownListFor(m => m.DealerID, new SelectList((IEnumerable)TempData["Dealers"],"DealerID", "DealerNumber"), string.Empty, new {@class = "form-control"})
        @Html.ValidationMessageFor(m => m.DealerID, null, new {@class = "help-block"})
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.EmployeeID, "Employee",new {@class = "control-label"})
        @Html.DropDownListFor(m => m.EmployeeID, new SelectList((IEnumerable)TempData["Employees"],"EmployeeID", "FullName"),string.Empty, new {@class="form-control"})
        @Html.ValidationMessageFor(m => m.EmployeeID, null, new {@class = "help-block"})       
    </div>

    <div class ="ok-cancel-group">
        <input class="btn btn-primary" type="submit" value="Create" />
        @Html.ActionLink("Cancel", "List","Product",new {@class = "btn btn-primary"})
    </div>
}                                   

i always get null reference instead model in [HttpPost] action, but if i use ViewModel instead Model everything is ok (ViewModel code below)

public class ProductViewModel
{
    public Product Product { get; set; }
}

I think it cause model class has virtual properties, but anyway i don't understand why it's ok when i use ViewModel. Can anyone answer me? Thx in advance.

The virtual properties won't change the outcome. The issue is that the view is written to bind to the view model, therefore accepting the model isn't going to work. If you want to use the model; then bind the view to the model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM