loader
Loading...
WelCome TO My Blog
Asp.Net MVC 08 December 2017

Enum to SelectList in ASP.NET MVC

By dhiren

In this article, let us learn to populate DropDownList control using enumeration defined in our project. Enum or Enumeration is a data type which is used to define named constants. Since enum members have string names and an integer value associated with it it can be used to populate DropDownList control. 

Step 1: Define your enum in a class

public enum Status

{

NEW = 1,

READY = 2,

IN_PROGRESS = 3,

CANCELLED = 4,

}

 

Step 2: Create a class EnumClass & define method to bind data.

public class EnumClass

{

[Display(Name = “Status”)]

public SelectList Status{get;set;}            

public string SelectedStatus { get; set; }

 

private List<KeyValuePair<string, string>> StatusList()

{

List<KeyValuePair<string, string>> orderList = new List<KeyValuePair<string, string>>();

foreach (var value in Enum.GetValues(typeof(Status)))

{

orderList.Add(new KeyValuePair<string, string>(((int)value).ToString(), ((Status)value).ToString()));

}

return orderList;

}

}

 

Step 3: Create a Controller. Create a get and post method for set and get the enum dropdown from view.

public ActionResult Index()

{

EnumClass model = new EnumClass ();

model.Status = new SelectList(this.StatusList(), “Key”, “Value”);

return View(model);

}

[HttpPost]

public ActionResult Index(EnumClass model)

{

Response.Write(model.SelectedStatus);

model.Status = new SelectList(this.StatusList(), “Key”, “Value”);

return View(model);

}

 

Step 5:Create View. That will display dropdown list from enum. 

@model ENUMtoSelectList.Models. EnumClass

@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<meta name=”viewport” content=”width=device-width” />

<title>Index</title>

</head>

<body>

@using (@Html.BeginForm(“Index”, “Home”, FormMethod.Post))

{

<div>

<label>@Html.DisplayNameFor(m => m.Status)</label>

<div class=”controls”>@Html.DropDownListFor(m => m.SelectedStatus, Model.Status, “ALL”, new { id = “memberStateSelect” })</div>

</div>

<input type=”submit” value=”Submit” />

}

</body>

</html>

Hope you like it. Stay tuned for more..wink

Leave a Comment

Only registered users can comment.


View Comments