Pages

Tuesday, November 9, 2010

Bind data to dropdown list in ASP.Net MVC

To add items to Drop down list in ASP.Net MVC

In view page give,
< % = Html.DropDownList("DDLSample") % >

Here DDLSample is the View Data name. And its value will be assigned in the controller.
In controller, in ActionResult methods give the following

For adding static values to Drop down list,


IList ilSelectList = new List();
for(int i=0; i<10; i++)
{
SelectListItem sl = new SelectListItem ();
sl.Text = "DDlItem" + i.ToString();
sl.Value = i.ToString();
ilSelectList.Add (sl);
}
ViewData["DDLSample"] = ilSelectListItems;

For binding values from data base

SelectList ddlDesignation = new SelectList(_db.Designation, "Value Field", "Text Field", "DefaultValuetoBeSelected");
ViewData["DDLSample"] = ddlDesignation