Easiest way to specify the selected option to a dropdown list in ASP.NET MVC
Posted
by sdr
on Stack Overflow
See other posts from Stack Overflow
or by sdr
Published on 2010-04-14T23:06:25Z
Indexed on
2010/04/15
7:03 UTC
Read the original article
Hit count: 268
I have a list of options (IEnumerable< SelectListItem >) in my model that I want to use in multiple dropdowns in my view. But each of these dropdowns could have a different selected option.
Is there an easy way to simply specfiy which should be selected if using the Html.DropDownList helper?
At this point, the only way I can see is to generate the html myself and loop through the list of options like so:
<% for(int i=0; i<10; i++) { %>
<select name="myDropDown<%= i %>">
<% foreach(var option in Model.Options) { %>
<option value="<%= Html.Encode(option.optValue) %>" <%if(ShouldBeSelected(i)) {%> selected="selected"<% } %>><%= Html.Encode(option.optText) %></option>
<% } %>
</select>
<% } %>
© Stack Overflow or respective owner