I want to add a DropDownList
in my Insert
View.
Controller:
public ActionResult Create() { ViewBag.CategoryList = new SelectList(Category.GetCategories()); return View("Insert", new Category()); }
View:
@Html.DropDownListFor(model => model.Category, (IEnumerable<SelectListItem>) (ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" })
The Category
class has only one string
field named Title
. Instead of getting the value of Title
I'm getting WebApplication.Models.Category
.
CodePudding user response:
Check that the Title
is defined as property and not a field to be data binding work properly.
Then try the following:
public ActionResult Create()
{
ViewBag.CategoryList = Category.GetCategories();
return View("Insert", new Product());
}
And in the Insert
view:
@using WebApplication1.Models @* Category namespace *@
@model WebApplication1.Models.Product
@{
IEnumerable<Category> categories = (IEnumerable<Category>)ViewBag.CategoryList;
}
@Html.DropDownListFor(m => categories.GetEnumerator().Current,
categories.Select(d =>
{
return new SelectListItem() { Text = d.Title, Value = d.Title };
}),
"Select Category", new { @class = "form-control" })