Here is an example of how to use the Html.DropDownList helper method available in the MVC framework to generate a combo in you page.
Let’s use the Northwind example and say that you want to create a product and in the product for you need to select a category to which this product belongs in a dropdownlist.
The first step is in the select the list of categories in the appropriate controller action. In my case I’m going to use the new Action.
public ActionResult New()
{
ViewData["CatList"] = new SelectList(_db.Categories.ToList(), "CategoryID", "CategoryName");
return View();
}
Notice that I used the SelectList class. In this case I used the constructor that takes 3 parameters:
- The list of categories I got from my Linq DataContext
- The name of the property of the Category class that has the ID value that is going to be stored in the select list and which will be the value that actually is passed to the Product class
- The name of the property of the Category class that has the value I want to display to the user
The SelectList class will be used by the DropDownList helper to generate the html code. Here is part of the View code:
...
<tr>
<td>Category:</td>
<td><%= Html.DropDownList("CategoryID",(SelectList)ViewData["CatList"]) %></td>
</tr>
...