Trying to get my project updated to MVC3, something I just can't find:
I have a simple datatype of ENUMS:
public enum States()
{
AL,AK,AZ,...WY
}
Which I want to use as a DropDown/SelectList in my view of a model that contains this datatype:
public class FormModel()
{
public States State {get; set;}
}
Pretty straight forward: when I go to use the auto-generate view for this partial class, it ignores this type.
I need a simple select list that sets the value of the enum as the selected item when I hit submit and process via my AJAX - JSON POST Method.
And than the view (???!):
<div class="editor-field">
@Html.DropDownListFor(model => model.State, model => model.States)
</div>
thanks in advance for the advice!
As of ASP.NET MVC 5.1 (RC1),
EnumDropDownListFor
is included by default as an extension method ofHtmlHelper
.The easiest answer in MVC5 is Define Enum:
Bind In View:
I made the following change to the SelectList method to make it work a little better for me. Maybe it will be useful for others.
I've just made one for my own project. The code below is part of my helper class, I hope that I got all methods needed. Write a comment if it doesn't work, and I'll check again.
Use it as:
Update
I've created alternative Html Helpers. All you need to do to use them is to change your baseviewpage in
views\web.config
.With them you can just do:
More info here: http://blog.gauffin.org/2011/10/first-draft-of-my-alternative-html-helpers/
Based on the accepted answer by @jgauffin, I've created my own version of
EnumDropDownListFor
, which deals with the problem of selecting items.The problem is detailed in another SO answer here:, and is basically down to a misunderstanding of the behaviour of the different overloads of
DropDownList
.My full code (which includes overloads for
htmlAttributes
etc is:I've written this up on my blog here.
If you want something really simple then there's another way, depending on how you store the state in the database.
If you had an entity like this:
Then generating the dropdown would be as easy as this:
Isn't LINQ pretty?