tags:

views:

2613

answers:

2

I would like to declare a combo box in a view in an ASP.NET MVC application, for letting the user select a lookup value. I know how to declare plain text boxes but is there an official helper for declaring combo boxes (date time pickers and the rest)?.

I also don't know what structure I should pass to my view for giving the values to the combo box. I assume I need both an id and a description.

Finally, how do I pass the selected id from the combo box back to my action in the controller?

+1  A: 

You might check out this blog entry by Scott Guthrie about Handling Form Edit Post Scenarios. He uses a drop down list in an example of his.

You can provide a list of complex objects to the drop down list too (Scott Guthrie's example doesn't show that, but it eludes to it).

You can do something like this...

<%= Html.DropDownList("Select One", "CategoryId", ViewData.Model.Categories, "Id", "Name", ViewData.Model.SelectedCategoryId)) %>

"Id" and "Name" refer to properties on your ViewData.Model.Categories list of objects.

If SelectedCategoryId has a value, then it will default the dropdownlist.

Elijah Manor
I tried to do what you suggested. The problem is I cannot find DropDownList. In the article it says I should include some MVC library that I cannot locate on my disk. Do you happen to know where I can find it?
Petros
+1  A: 

If you have a table of Product Types with description and a value ( id ) that you want to map to your dropdown then do the following inside your action in the controller.

//Lets assume you retrieve your product types somehow here
ViewData["ProductTypes"] =  new List<ProductType>();

Then inside your view type the following <%= Html.DropDownList("productType", new SelectList((IEnumerable)ViewData["ProductTypes"], "TypeID", "Description"))%>

TypeID and Description refers to the properties of your object of type ProductType

Also, you might not find Html.DropDownList if you have an older version of MVC installed, make sure you have a Beta+ version before you try this out.

Konstantinos