I have this annoying problem where my DropDownlist doesn’t select the current value by default.
Controller:
var YearsCycling = new SelectList(new List<SelectListItem>()
{
new SelectListItem(){ Value="1yr", Text="1yr"},
new SelectListItem(){ Value="1-3yrs", Text="1-3yrs"},
new SelectListItem(){ Value="3-5yrs", Text="3-5yrs"},
new SelectListItem(){ Value="5-10yrs", Text="5-10yrs"},
new SelectListItem(){ Value="10+yrs", Text="10+yrs"}
},
"Value",
"Text",
new SelectListItem() { Value = "5-10yrs", Text = "5-10yrs",
Selected = true });
ViewBag.YearsCycling = YearsCycling;
View:
<%:Html.DropDownListFor(model=>model.YearsCycling,(SelectList)ViewBag.YearsCycling,"-select-") %>
but instead of selecting “5-10yrs”, it just shows the “-select-” option and if I inspect the DOM source, none of the elements are selected.
UPDATE: I still don’t know what the problem is, but I got it working for now by doing something ugly:
<%
var sl = (SelectList)ViewBag.YearsCycling;
%>
<select name="YearsCycling" id="YearsCycling">
<%foreach(var li in sl){ %>
<option value="<%:li.Value %>" <%if(li.Selected){%>selected="true"<%}%>><%:li.Text %></option>
<%} %>
</select>
This isn’t the best solution, but if you’ve come to this question because you’ve been pulling your hair out, this should help.
Your code should be.
You could use this overload instead.