[英]ASP.NET MVC | DropDownListFor gives error Object reference not set to an instance of an object
我想在下拉菜单中查看。
但该下拉菜单应具有从数据库加载的类别。
我在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>
初始化CreateProductModel
属性:
var model = new ProductModel();
model.CreateProductModel = new CreateProductModel();
model.CreateProductModel.Categories = new SelectList(_db.Categories, "CategoryID", "Name", 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.