Click here to Skip to main content
15,894,720 members

Response to: ASP.NET MVC - Help needed to Improve the code for mvc's Drop-Down Box?

Revision 2
Hi,

Try the following code

C#
[HttpGet]
public ActionResult Index()
{
     ViewBag.CitiesDropDown = GetCityList();
     return View();
}


private List<selectlistitem> GetCityList()
{
     //Here you can access DB to get your required data. Just make sure the return type
     List<selectlistitem> itemList = new List<selectlistitem>();
     itemList.Add(new SelectListItem { Text = "City1", Value = "1", Selected = true });
     itemList.Add(new SelectListItem { Text = "City2", Value = "2", Selected = true });
     itemList.Add(new SelectListItem { Text = "City3", Value = "3", Selected = true });
     return itemList;
}

and then in your view

HTML
@Html.DropDownList("City_Code", ViewBag.CitiesDropDown as List<selectlistitem>, "")</selectlistitem>



Hope this simplifies you :)
Posted 16-Jan-13 3:02am by Sheikh Muhammad Haris.
Tags: , , ,