Reputation: 23749
In one of our ASP.NET MVC 4 views, we have a DropDownListFor (along with other html controls) as follows:
@Html.DropDownListFor(model=>model.ProductType,
(List<SelectListItem>)ViewBag.ProductType,
"--- Select Product Type ----")
The list is getting populated from a database lookup table. When we click on the submit button, all the controls values including the selected value of the dropdownlist get inserted into the database successfully. But when the page is displayed the dropdown's selected value always shows "--- Select Product Type ----" instead of the value that was inserted into the database.
Please help. Thanks.
Upvotes: 0
Views: 1231
Reputation: 15360
You need to set the selected value in your SelectList inside your Controller i.e. ViewBag.ProductType.
Have a look at the overloads for SelectList class.
http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.118).aspx
public ActionResult MyMethod()
{
var items = db.ProductType.ToList();
var selectedItem = items.FirstOrDefault(x => get desired selected item);
ViewBag.ProductType =
new SelectList(items, "ProductID", "ProductType", selectedItem);
}
Upvotes: 2