DropDownListFor enums in EF5

2019-02-16 10:21发布

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.

2条回答
别忘想泡老子
2楼-- · 2019-02-16 10:37

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.

查看更多
Root(大扎)
3楼-- · 2019-02-16 10:48

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.

查看更多
登录 后发表回答