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.
I'm sure you're way past this, but I just got burned on this a moment ago because I had named the dropdown list the same name as the property in my view model class.
Changing the dropdown list name to something else cured it right up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With