ASP.NET MVC | DropDownListFor给出错误对象引用未设置为对象的实例

时间:2015-10-18 09:56:46

标签: c# asp.net-mvc

我希望在我看来有一个下拉列表。

但该下拉列表应该从数据库加载类别。

我在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 个答案:

答案 0 :(得分:2)

初始化CreateProductModel属性:

var model = new ProductModel();
model.CreateProductModel = new CreateProductModel();
model.CreateProductModel.Categories = new SelectList(_db.Categories, "CategoryID", "Name", 1);
相关问题