2015-10-18 37 views
0

我想在我的视图中有一个下拉列表。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> 

我收到此错误.. enter image description here

+1

由于ProductModel'的'了'CreateProductModel'属性为null(你需要初始化第一 - 'model.CreateProductModel =新CreateProductModel();' –

回答

2

初始化CreateProductModel属性:

var model = new ProductModel(); 
model.CreateProductModel = new CreateProductModel(); 
model.CreateProductModel.Categories = new SelectList(_db.Categories, "CategoryID", "Name", 1); 
+0

非常感谢。你真棒..它的工作:) –

+0

@SizzlingCode你能接受这个答案吗? – Backs

+1

当时它显示7分钟等待接受回答:) –

相关问题