Create EnumDropDownList in MVC 5

In this blog, I will demonstrate how to create a EnumDropDownList in MVC 5 razor view, which is a valuable replacement of DropDownList.  In earlier version of MVC framework  Enum was not supported in View.

Create a Model with Enum type   

First of all we will create a Model which will have enum property. Here is a sample EnumTest Model
  1. Namespace Blog{  
  2.   
  3. public class EnumTest  
  4. {  
  5.    public int BlogId {get;set;}  
  6.    public string BlogName {get;set;}  
  7.    public Roles UserRole {get;set;}   
  8. }   
  9. public enum Roles  
  10. {  
  11.    Admin,  
  12.    Moderator,  
  13.    Contributor  
  14. }  
  15. }  

Now will create a Controller 

Here is a simple controller with Index Action
  1. public class Blog : Controller  
  2. {  
  3.     public ActionResult Index()  
  4.     {  
  5.         return View();  
  6.     }  
  7.      [HttpPost]  
  8.     public ActionResult Index(EnumTest model)  
  9.     {  
  10.         return View();  
  11.     }  
  12. }  
Razor view 
 
Now we will use Roles in view using html helper @Html.EnumDropDownListFor
  1. @model Blog.EnumTest     
  2. <div >    
  3.     @Html.TextBoxFor(model=>model.BlogName) </br>  
  4.     @Html.EnumDropDownListFor(model => model.Role) </br>    
  5.         
  6. </div>    
 .....................and we are done.
 
Its no need to work with SelectList anymore, and it's quite simple to work with DropDownList with enums.
 
I have found many questions on C-sharpcorner and other communities on DropDownList. With MVC 5 I hope will not see any more queries on it.
Ebook Download
View all
Learn
View all