If you want to bind a dropdown list in MVC with Enum then this article is surely for you. In this article I will show how can we bind a DropDownList with Enum with the help of SelectList in MVC.
Mostly we bind dropdown list with a list coming from database but let suppose I have a list of four-five records and I want to show these items in dropdown list. In this case I don't want to first save these in database and then retrieve from database as list and binding to my dropdown list. What if I can create a simple Enum for my list and can bind my dropdown list with this. Here in this article I will try to explain, how can we bind a dropdown list from a enum in MVC.
Let's start step by step. I will start with Enum first.
I am creating a sample enum for category. Below is my sample enum with few records.
enum CategoryEnum { Account=1, Admin=2, HR=3, Employee=4}
Now I am creating a controller and naming it as ExampleController and will put some code in it to create a list from enum and put in ViewData. Below is my controller code. My function GetEnumList() is simply creating a SelectList from enum and adding DataValue and DataText to it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
public class ExampleController : Controller
{
public ActionResult Index()
{
ViewBag.Category = GetEnumList();
return View();
}
SelectList GetEnumList()
{
var list = from CategoryEnum e in Enum.GetValues(typeof(CategoryEnum))
select new { ID = (int)e, Category = e.ToString() };
return new SelectList(list, "ID", "Category", 2);
}
}
At last it is time to create a view for my sample so that I can see my dropdown here. So let's create a view. Below is the code for my view.
<h2>Bind DropDownList with Enum</h2>
<div class="section">
<div class="line">
<div class="line-heading">Name</div>
<div class="line-input"><input type="text"/> </div>
</div>
<div class="line">
<div class="line-heading">Category</div>
<div class="line-input">@Html.DropDownList("CategoryId", (SelectList)ViewBag.Category, "---Select----")</div>
</div>
<div class="line">
<div class="line-heading"> </div>
<div class="line-input"><input type="button" id="btn" name="btn" value="Click to test" /></div>
</div>
</div>
I am adding few lines of script so that I can test my implementation.
<script>
$("#btn").on("click", function () {
alert($("#CategoryId").val());
});
</script>
And I am done. See how simple it was. So use it and try yourself. Hope it helps you.