Right now, I'm trying to create an edit page for an MVC application that utilizes a drop-down list, allowing the user to edit an employee's location. I consider two scenarios: one where the employee has no set location, and one in which the employee already has an assigned location. In the second case, I would like the drop down list in the edit page to automatically have the current location selected in the list. The list is successfully created, however it defaults to the first value (in this case the empty string) in the SelectList, NOT the currently selected value. The controller code for this case is as follows:
var pairs = db.Locations.Select(x => new { value = x.LocationID, text = x.City }).ToList();
pairs.Insert(0, (new {value = 0, text = ""}));
SelectList Locations = new SelectList(pairs,
"value", "text", pairs.First(x=> x.value == employee.Location.LocationID));
foreach (SelectListItem item in Locations)
{
item.Selected = false;
}
foreach (SelectListItem item in Locations)
{
if (item.Value == (employee.Location.LocationID.ToString()))
{
Debug.Print("Match Found");
item.Selected = true;
break;
}
}
ViewBag.Locations = Locations;
Note that right now, I am explicitly enumerating over the list, and flagging the desired value as selected. Originally, I used the overload for the SelectList constructor that took a "selectedValue" parameter, however this did not work either. Also note the print statement: when running, that line is indeed printed, meaning that the matched value was found and flagged. It simply does not display as such on the page.
The code in the view is as follows:
<div class="form-group">
@Html.Label("Location", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("location", ViewBag.Locations as IEnumerable<SelectListItem>)
</div>
</div>
Is there something that I'm missing?
Thanks!