DropDownListFor enums in EF5

做~自己de王妃 提交于 2019-12-19 05:16:24

问题


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.



来源:https://stackoverflow.com/questions/12460152/dropdownlistfor-enums-in-ef5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!