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
- Namespace Blog{
-
- public class EnumTest
- {
- public int BlogId {get;set;}
- public string BlogName {get;set;}
- public Roles UserRole {get;set;}
- }
- public enum Roles
- {
- Admin,
- Moderator,
- Contributor
- }
- }
Now will create a Controller
Here is a simple controller with Index Action
- public class Blog : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- [HttpPost]
- public ActionResult Index(EnumTest model)
- {
- return View();
- }
- }
Razor view
Now we will use Roles in view using html helper
@Html.EnumDropDownListFor
- @model Blog.EnumTest
- <div >
- @Html.TextBoxFor(model=>model.BlogName) </br>
- @Html.EnumDropDownListFor(model => model.Role) </br>
-
- </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.