Assuming that your
Address
class contains
ID ,City
... attribute, the code below will explain to you how to bind
DropDownList
easily in Asp.NET MVC application.
1. In
Model
folder define the Address and Address Collection class,
public class Address{
public int ID{get;set};
public string City{get;set};
}
public class Addresses:List<Address> {
public Addresses() {
this.Add(new Address() {ID=1, City="A"});
this.Add(new Address() {ID=2, City="B"});
}
}
2 In
Contoller
class that is going to consume the Address collection as follow.
public ActionResult Index()
{
Addresses addresses = new Addresses();
ViewBag.Addresses= new SelectList(addresses.AsEnumerable(), "ID","City");
return View();
}
3. In the
View
page consume the
ViewBag.Addresses
values as follow.
@Html.DropDownList("address", (SelectList)ViewBag.Addresses, "All Addresses")