MVC3 Razor DropDownListFor Enums

2019-01-03 01:25发布

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!

13条回答
在下西门庆
2楼-- · 2019-01-03 02:04

This is most generic code which will be used for all Enums.

public static class UtilitiesClass
{

    public static SelectList GetEnumType(Type enumType)
    {
        var value = from e in Enum.GetNames(enumType)
                    select new
                    {
                        ID = Convert.ToInt32(Enum.Parse(enumType, e, true)),
                        Name = e
                    };
        return new SelectList(value, "ID", "Name");
    }
}

Action Method

ViewBag.Enum= UtilitiesClass.GetEnumType(typeof (YourEnumType));

View.cshtml

 @Html.DropDownList("Type", (IEnumerable<SelectListItem>)ViewBag.Enum, new { @class = "form-control"})
查看更多
登录 后发表回答