How to bind enum to dropdownlist in mvc razor

How to bind enum to dropdownlist in mvc razor

In this tutorial i am going to explain about how to bind enum to dropdownlist in mvc razor. In my previous tutorial i have explained about

Implementation how to bind enum to dropdownlist in mvc razor.:

Now we will see the implementation of how to bind enum to dropdownlist in mvc razor.

Add Employee Model:

Open visual studio and create a new mvc project. Once the project is loaded, right click on model folder and the new model. Name it as Employee. Add the below code in the Employee.cs

The above code contains Employee model and DepartmentEnum enum.

Add Employee Controller:

Now right click on controller folder, and add a new controller called EmployeeController. After that create a new action method called Create and add the below code. In the below code i have converted the enum into selectlist and passing it in the viewbag from controller to view.

Add View:

Right click on the action method and add view to Create action method using Create template and Employee model. Below is the generated view.

Now open the RouteConfig.cs in AppStart folder and set the default controller to Employee controller and default action to Create action method.

Now if you run the application you can see the output. The problem with this code is everytime we need to write code to convert the enum to selectlist.

Create Enum Extension Method

To overcome this redundant work i have created an extension method. Right click on the project and add new folder named Helpers. Now add a class called ExtensionMethods inside the folder. Write the below code inside the ExtensionMethods file.

Now to use the extension method i have created another action method CreateWithEnumExtension. Below is the action method code.

Alternatively you can directly call the enum extension method directly from the view like below.

Please note while calling extension method you can pass the default selected item. Below is my complete CreateWithEnumExtension.cshtml view code.

Below is my complete employee controller code..

Output:

Now if you run the program you can see the output of how to bind enum to dropdownlist in mvc razor.

Conclusion:

Hope you learned how to bind enum to dropdownlist in mvc razor. Do you like this tutorial? Help us to improve. Please post your comments and feedback below.

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!