Note that there are some explanatory texts on larger screens.

plurals
  1. POSelected Item in Dropdown Lists from Enum in ASP.net MVC
    text
    copied!<p>Sorry if this is a dup, my searching turned up nothing.</p> <p>I am using the following method to generate drop down lists for enum types (lifted from here: <a href="http://addinit.com/?q=node/54" rel="noreferrer">http://addinit.com/?q=node/54</a>):</p> <pre><code>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 &amp;&amp; selected.GetType() != type) throw new ArgumentException("Selected object is not " + type.ToString()); var enums = new List&lt;SelectListItem&gt;(); 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--"); } </code></pre> <p>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:</p> <pre><code>&lt;%= Html.DropDownList("fam", typeof(EnumFamily), Model.Family)%&gt; </code></pre> <p>But this doesn't:</p> <pre><code>&lt;%= Html.DropDownList("family", typeof(EnumFamily), Model.Family)%&gt; </code></pre> <p>Because I'm trying to pass an entire object directly to the controller method I am posting to, I would <em>really</em> 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.</p> <p>I don't think this matters but I am running MVC 1 on mono 2.6</p> <p><strong>edit:</strong> I just tested this on windows, and I am seeing the same behavior</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload