Dropdown in ASP.NET MVC 2
I have following ViewModel containing "NumberOfAdults" fields.
public开发者_如何学Go class SearchView
{
public int NumberOfAdults { get; set; }
// More fields...
}
Assuming it will have some value (lets say 5) populated from some configuration file and I have a strongly typed View. What is the best way to populate a dropdown containing text and values of 1,2,3,4,5 without hard coding <Select...><Option value="1">1</Option></Select>
? Is there a MVC way of doing it?
I wouldn't be surprised if there's a helper that I'm not thinking of that could build the SelectList more elegantly, but this works.
<%
// Build a list of SelectListItem from 1 to N
List<SelectListItem> options = new List<SelectListItem>();
for (int i = 1; i <= Model.NumberOfAdults; i++)
{
string stringValue = i.ToString();
SelectListItem item = new SelectListItem() { Value = stringValue, Text = stringValue };
options.Add(item);
}
%>
<%= Html.DropDownList("yourName", options) %>
This renders:
<select id="yourName" name="yourName">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
精彩评论