Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDownListFor enums in EF5

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.

like image 892
Tim Avatar asked Sep 17 '12 13:09

Tim


2 Answers

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.

like image 169
Tim Avatar answered Nov 10 '22 05:11

Tim


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.

like image 5
demoncodemonkey Avatar answered Nov 10 '22 05:11

demoncodemonkey