Selected Item in Dropdown Lists from Enum in ASP.net MVC
Posted
by AlexCuse
on Stack Overflow
See other posts from Stack Overflow
or by AlexCuse
Published on 2010-06-13T15:25:16Z
Indexed on
2010/06/13
15:52 UTC
Read the original article
Hit count: 607
asp.net-mvc
Sorry if this is a dup, my searching turned up nothing.
I am using the following method to generate drop down lists for enum types (lifted from here: http://addinit.com/?q=node/54):
public static string DropDownList(this HtmlHelper helper, string name, Type type, object selected)
{
if (!type.IsEnum)
throw new ArgumentException("Type is not an enum.");
if(selected != null && selected.GetType() != type)
throw new ArgumentException("Selected object is not " + type.ToString());
var enums = new List<SelectListItem>();
foreach (int value in Enum.GetValues(type))
{
var item = new SelectListItem();
item.Value = value.ToString();
item.Text = Enum.GetName(type, value);
if(selected != null)
item.Selected = (int)selected == value;
enums.Add(item);
}
return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, enums, "--Select--");
}
It is working fine, except for one thing. If I give the dropdown list the same name as the property on my model the selected value is not set properly. Meaning this works:
<%= Html.DropDownList("fam", typeof(EnumFamily), Model.Family)%>
But this doesn't:
<%= Html.DropDownList("family", typeof(EnumFamily), Model.Family)%>
Because I'm trying to pass an entire object directly to the controller method I am posting to, I would really like to have the dropdown list named for the property on the model. When using the "right" name, the dropdown does post correctly, I just can't seem to set the selected value.
I don't think this matters but I am running MVC 1 on mono 2.6
© Stack Overflow or respective owner