DropDownListFor enums in EF5

2019-02-16 10:08发布

问题:

using MVC4 Razor and Entityframework 5. I have a table called organisation with a integer TypeID field which i have created an enum type. In the code i can set and compare the typeid using the enum.

 public enum OrganisationType : int
    {
        Company = 1,
        Department = 2,
        Location = 4
    }

However when i generate the create.cshtml either using the default vs2012 mvc 4 razor templates, or the via the mvcscaffolding nuget package both ignore the TypeID field. I was thinking of amending the tt templates so that they are autogenerated. But initially is it possible to display the descriptive name of the enum in a dropdownlistfor.

回答1:

This is the solution, its just a shame that its not simple to modify the TT templates to automate this.

@Html.DropDownListFor(model => model.TypeID, new SelectList(Enum.GetValues(typeof(Models.OrganisationType))))

This displays a dropdowncombo with the Textual values in it i.e. company, department, location.



回答2:

In the current version of MVC5, if you scaffold a view for a model that has an enum, it will generate this:

@Html.EnumDropDownListFor(model => model.OrganisationType,
                          htmlAttributes: new { @class = "form-control" })

which does exactly the same as Tim's solution but with slightly nicer syntax.