Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC dropdownlist not selecting value on render

Tags:

asp.net-mvc

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.

like image 311
Captain Kenpachi Avatar asked Jan 30 '13 13:01

Captain Kenpachi


1 Answers

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.

like image 177
Brian Avatar answered Sep 20 '22 13:09

Brian