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

3 comments:

  1. Can u show me some code with which I can post my HTML.ListBoxfor values back to controller ?

    ReplyDelete
  2. can u explain mor .i want to data in dropdown list from database.and i want this in mvc3..

    ReplyDelete
  3. hi all,

    This link we can get the brief explanation about drop down data binding in MVC

    http://csharpektroncmssql.blogspot.in/2012/07/bind-data-to-dropdownlist-in-aspnet.html

    ReplyDelete