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
  1. public class MyData
  2.     {
  3.         public int Id { get; set; }
  4.  
  5.         public MyEnum Enum1 { get; set; }
  6.  
  7.         public MyEnum? Enum2 { get; set; }
  8.  
  9.         public FlagsEnum FlagsEnum { get; set; }
  10.     }

 

Enum as Dropdown List

 

  1. <div class="form-group">
  2.          @Html.LabelFor(model => model.Enum1, new { @class = "control-label col-md-2" })
  3.          <div class="col-md-10">
  4.              @Html.EditorFor(model => model.Enum1)
  5.              @Html.ValidationMessageFor(model => model.Enum1)
  6.          </div>
  7.      </div>
  8.  
  9.      <div class="form-group">
  10.          @Html.LabelFor(model => model.Enum2, new { @class = "control-label col-md-2" })
  11.          <div class="col-md-10">
  12.              @Html.EditorFor(model => model.Enum2)
  13.              @Html.ValidationMessageFor(model => model.Enum2)
  14.          </div>
  15.      </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.

image

Enum as Radio button List

 

  1. <div class="form-group">
  2.           @Html.LabelFor(model => model.Enum1, new { @class = "control-label col-md-2" })
  3.           <div class="col-md-10">
  4.               @Html.EditorFor(model => model.Enum1, templateName: "Enum-radio")
  5.               @Html.ValidationMessageFor(model => model.Enum1)
  6.           </div>
  7.       </div>
  8.  
  9.       <div class="form-group">
  10.           @Html.LabelFor(model => model.Enum2, new { @class = "control-label col-md-2" })
  11.           <div class="col-md-10">
  12.               @Html.EditorFor(model => model.Enum2, templateName: "Enum-radio")
  13.               @Html.ValidationMessageFor(model => model.Enum2)
  14.           </div>
  15.       </div>
 

image

Happy Coding !!!!!!!!!!

Comments

Popular posts from this blog

Responsive Web Design

Affine Cipher in C#

Contract First Development in WCF 4.5