当我在模型类中使用导航属性时,Null Reference Exception

时间:2013-12-02 13:28:46

标签: c# asp.net-mvc entity-framework model asp.net-mvc-viewmodel

我尝试在控制器操作中在数据库中添加新实体 这是我的模型类

    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; }
}

这是在数据库中创建新产品的行动

    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具有适当的模型类型(在这种情况下为产品类型)。代码

    @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>
}                                   

我总是在[HttpPost]动作中获取null引用而不是模型,但如果我使用ViewModel而不是模型一切正常(ViewModel代码如下)

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

我认为它导致模型类具有虚拟属性,但无论如何我不明白为什么当我使用ViewModel时它是可以的。 谁能回答我? Thx提前。

1 个答案:

答案 0 :(得分:2)

virtual属性不会改变结果。问题是视图被编写为绑定到视图模型,因此接受模型不起作用。如果你想使用该模型;然后将视图绑定到模型。