Reputation: 103497
Are there any helpers for displaying dropdownlists in asp.net-mvc?
I have an enumeration that I need to populate, and pre-select in a dropdownlist.
Upvotes: 0
Views: 247
Reputation: 28745
The FluentHtml library from MVC Contrib has built-in support for generating select boxes from enumerations.
<%= this.Select("example")
.Options<System.IO.FileOptions>()
.Selected(System.IO.FileOptions.Asynchronous) %>
This outputs:
<select id="example" name="example">
<option value="0">None</option>
<option value="16384">Encrypted</option>
<option value="67108864">DeleteOnClose</option>
<option value="134217728">SequentialScan</option>
<option value="268435456">RandomAccess</option>
<option selected="selected" value="1073741824">Asynchronous</option>
<option value="-2147483648">WriteThrough</option>
</select>
Upvotes: 2
Reputation: 116977
<%= Html.DropDownList() %>
has about 8 overloads that you can use. You'll need to map your enumeration into an IEnumerable<SelectListItem>
to pass to it though. Something like this:
var names = Enum.GetNames(typeof(MyEnum));
List<SelectListItem> items = new List<SelectListItem>();
foreach (var s in names)
{
items.Add(new SelectListItem() { Text = s,
Value = s,
Selected = (s == "SelectedValue") };
}
Upvotes: 1