我想在我的视图中有一个下拉列表。ASP.NET MVC | DropDownListFor给出错误对象引用未设置为对象的实例
但该下拉列表应该从数据库加载类别。
我使用实体框架代码优先方法在MVC 5
这里是我的
模型。
public class CreateProductModel
{
[Required]
public string Name { get; set; }
[Required]
public int CategoryID { get; set; }
public SelectList Categories { get; set; }
[MaxLength]
public double Price { get; set; }
public string Description { get; set; }
}
控制器:
public ActionResult Index()
{
var model = new ProductModel();
model.CreateProductModel.Categories = new SelectList(_db.Categories, "CategoryID", "Name", 1);
return View(model);
}
查看:
<div class="form-group">
@Html.LabelFor(model => model.CreateProductModel.CategoryID, new { @class = "col-lg-2 control-label" })
<div class="col-lg-10">
@Html.DropDownListFor(model => model.CreateProductModel.CategoryID, new SelectList(Model.CreateProductModel.Categories, "CategoryID", "Name", 1), "Please Select Category");
</div>
</div>
由于ProductModel'的'了'CreateProductModel'属性为null(你需要初始化第一 - 'model.CreateProductModel =新CreateProductModel();' –