I have a C#.Net MVC3 web app. I am using Drop Down lists all over the place and having success. However, there are two that I am having trouble with. The only difference is that I am creating the SelectLists
on the fly in the code rather than using Lookup tables. I use lookup tables for all the other Drop Downs. When I QuickWatch the SelectLists
in the code, the correct Item has the Selected
property value set to true
. However, when the page loads, the item with the Selected
property is not displayed. The first item is. Any ideas? This is one of those werid ones. I've tried both ways below. In both cases, the ViewBag.DateToYear and the SelectList DateToYear have the right values and 'Selected' properties set
1)
//Controller
IList<string> dateToYear = new List<string>();
for (int i = 0; i < numberYears; i++)
{
dateToYear.Add(DateTime.Now.AddYears(i).Year.ToString());
}
ViewBag.DateToYear = new SelectList(dateToYear,"2014")
//View
@Html.DropDownList("DateFromYear", (SelectList)ViewBag.DateToYear )
2) //Controller SAME as above
//View
List<SelectListItem> DateToYear = new List<SelectListItem>();
foreach (var m in ViewBag.DateToYear)
{
DateToYear.Add(new SelectListItem { Selected = @m.Selected, Value = @m.Text, Text = @m.Text });
}
@Html.DropDownList("DateFromYear", DateToYear)