Enum Support in MVC 5.1
Enum support for MVC views is a new feature introduced in Asp.net MVC 5.1. If you have Enum in your model view will create a dropdown list or radio button list in the view for you.
See the example below.
Model
- public class MyData
- {
- public int Id { get; set; }
- public MyEnum Enum1 { get; set; }
- public MyEnum? Enum2 { get; set; }
- public FlagsEnum FlagsEnum { get; set; }
- }
Enum as Dropdown List
- <div class="form-group">
- @Html.LabelFor(model => model.Enum1, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Enum1)
- @Html.ValidationMessageFor(model => model.Enum1)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Enum2, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Enum2)
- @Html.ValidationMessageFor(model => model.Enum2)
- </div>
- </div>
Following shows the how view renders. As you can see as Enum2 member is nullable it does not have any value selected by default.
Enum as Radio button List
- <div class="form-group">
- @Html.LabelFor(model => model.Enum1, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Enum1, templateName: "Enum-radio")
- @Html.ValidationMessageFor(model => model.Enum1)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Enum2, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Enum2, templateName: "Enum-radio")
- @Html.ValidationMessageFor(model => model.Enum2)
- </div>
- </div>
Happy Coding !!!!!!!!!!
Comments
Post a Comment