I have an asp.net-mvc website and i am running into an issue where the correct selected item in a dropdown is not being selected. I have the following code on my controller action (simplified to isolate the issue):
public ActionResult MyAction()
{
var vm = GetVM();
var list = new List<INamed> {new NamedInfo() {Id = 1, Name = "Yes"}, new NamedInfo() {Id = 0, Name = "No"}};
vm.YesNoList = SelectListHelper.GenerateDropdownList(vm.IncludesWeekends ? 1 : 0, list);
return View(vm);
}
and here is the definition of GenerateDropdownList
public static List<SelectListItem> GenerateDropdownList<T>(int id, IEnumerable<T> list) where T : INamed
{
List<SelectListItem> dropdown = list.Select(c => new SelectListItem
{
Selected = c.Id == id,
Text = c.ToString(),
Value = c.Id.ToString()
}).ToList();
return dropdown;
}
Below is the code in my HTML view:
<% = Html.DropDownList("IncludesWeekends", Model.YesNoList, new { @id = "IncludesWeekends" })%>
I expect No to be selected in my example (and it has Selected = true when i put a breakpoint on the server side but when i look at the html that is generated, nothing is selected:
<select id="IncludesWeekends" class="autoComplete1" name="IncludesWeekends">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
and "Yes" is selected by default because its teh first item.
Any suggestions on what i am doing wrong here or alternatives that work?