Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Tuesday, February 16, 2010

http://www.mikesdotnetting.com/Article/128/Get-The-Drop-On-ASP.NET-MVC-DropDownLists

1) SelectListItem – Value and Text property assigned

var db = new northwindDataContext();
IEnumerable<SelectListItem> items = db.Categories.Select(c => new SelectListItem {Value = c.CategoryID.ToString(), Text = c.CategoryName});
ViewData["CategoryID"] = items;
 
in the view:
<%= Html.DropDownList("CategoryID") %>

which is the pretty much the same as:
 
<%= Html.DropDownList("CategoryID", (IEnumerable<SelectListItem>)ViewData["Categories"]) %>

2) SelectList is tidier, and gives a couple of overloads including selected (in the case below number 3):
 
var query = db.Categories.Select(c => new {c.CategoryID , c.CategoryName});
ViewData["Categories"] = new SelectList(query.AsEnumerable(), "CategoryID", "CategoryName",3);

image
 

PostBack

On the product view:

<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "TheForm" })) {%> 
<%=Html.DropDownList("CategoryID", (SelectList)ViewData["Categories"], new { onchange="this.form.submit();"})%>
<%}%>

and the product controller:

public ActionResult Index(int? categoryid)
{
var db = new northwindDataContext();

var query = db.Categories.Select(c => new {c.CategoryID, c.CategoryName});
ViewData["Categories"] = new SelectList(query.AsEnumerable(), "CategoryID", "CategoryName");

List<Product> products;
if (categoryid == null)
products = db.Products.ToList();
else
products = (from p in db.Products
where p.CategoryID == categoryid
select p).ToList();
return View(products);
}

which gives:
 
image 
Used LinqToSQL.
ASP.NET MVC version 1
 

Run Implementation

Found I had to sort a generic list
 
The crowd goes wild:
image
All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview