Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a dropdown box in a view to set a value to a model in ASP.NET MVC?

Tags:

asp.net-mvc

I would like to declare a dropdown 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 dropdown 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 dropdown box. I assume I need both an id and a description.

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

like image 747
Petros Avatar asked Oct 13 '08 08:10

Petros


People also ask

How do I send a dropdown selected value?

If you want to pass the selected value of your dropdown list into your controller, just add a string parameter with the name drpFields (same as the first parameter of your DropDownList method) into your temp action method. Hope it will help you to fix your problem.


2 Answers

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.

like image 110
Konstantinos Avatar answered Oct 20 '22 02:10

Konstantinos


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 alludes 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.

like image 36
Elijah Manor Avatar answered Oct 20 '22 03:10

Elijah Manor