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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With