Reputation: 6070
I want to have a dropdown in my view, but that dropdown should have categories loaded from database.
I am using Entity Framework Code First Approach in MVC 5.
Here is my Model:
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; }
}
Controller:
public ActionResult Index()
{
var model = new ProductModel();
model.CreateProductModel.Categories = new SelectList(_db.Categories, "CategoryID", "Name", 1);
return View(model);
}
View:
<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>
I am getting this error:
Upvotes: 0
Views: 927
Reputation: 24903
Initialize CreateProductModel
property:
var model = new ProductModel();
model.CreateProductModel = new CreateProductModel();
model.CreateProductModel.Categories = new SelectList(_db.Categories, "CategoryID", "Name", 1);
Upvotes: 2