簡體   English   中英

ASP.NET MVC | DropDownListFor給出錯誤的對象引用未設置為對象的實例

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM