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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With