我想在我的視圖中有一個下拉列表。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();' –