Reputation: 2970
In my project, Html.DropdownList could not display its selected value.It displays the initial value of the list.My controller and view codes are given below:
Controller:
public ActionResult Edit(int id = 0)
{
PERMISSION permission = permissionManager.Find(id);
ViewBag.MODULE_ID = new SelectList(moduleManager.GetAll(), "ID", "TITLE",permission.MODULE_ID);
return View(permission);
}
View :
@Html.DropDownList("MODULE_ID", (IEnumerable<SelectListItem>)@ViewBag.MODULE_ID, new { @class = "form-control" })
But if I write :
@Html.DropDownList("MODULE_ID", String.Empty)
It works fine.but I have to add the class="form-control".What should be solution?
UPDATE:
I have changed the ViewBag name from ViewBag.MODULE_ID to ViewBag.ModuleList. It may conflicts with the name of the dropdownlist. and now It works fine.
Upvotes: 2
Views: 5338
Reputation: 1408
what works for me according to previous solution: in controller:
ViewBag.VCenter = new SelectList(db.VirtualMachinesData.Where(x => x.IsVCenter == true).ToList(), "Id", "IPAddress","80"); ;
in View:
@Html.DropDownList("v", (IEnumerable<SelectListItem>)@ViewBag.VCenter, new { @class = "form-control" })
Important note: the name of dropdownlist -"v"- must be different from the name of viewbag -"VCenter"-, if same names it didn't work.
Upvotes: 0
Reputation: 2970
I have changed the ViewBag name from ViewBag.MODULE_ID to ViewBag.ModuleList. It may conflicts with the name of the dropdownlist. and now It works fine.
Upvotes: 4
Reputation: 6148
You are adding the form-control
class in the wrong parameter. currently it is being added as the option label.
Use this:
@Html.DropDownList("MODULE_ID", (IEnumerable<SelectListItem>)@ViewBag.MODULE_ID, "-- Select --", new { @class = "form-control" })
On a side note, you should consider using a ViewModel class and doing away with both the magic string "MODULE_ID"
and the ViewBag
magic property. A ViewModel class allows you to strongly name things without casting, like this:
@Html.DropDownListFor(model => model.MODULE_ID, Model.Modules, "-- Select --", new { @class = "form-control" })
It's a subtle looking change but everything is compile time checked.
Upvotes: 1