I’m trying to teach myself MVC3. Im converting from webforms.
I need to create a view model that includes a dropdown list that I can pass to the controller and eventually render in the View.
How can I accomplish this? I have the skeleton but I dont know what the code is to actually create the name value pairs for the view.
namespace DH.ViewModels
{
public class SharedLayoutViewModel
{
public IEnumerable<SelectListItem> Products
{
//some code to setup the value/name pairs to be rendered in the view.
//example:
//<option value="1">Mustard</option>
//<option value="2">Ketchup</option>
//<option value="3">Mayo</option>
//<option value="4">Relish</option>
//<option value="5">BBQ</option>
}
}
}
Thanks
I would create a class for Product and the create Products Property in my main viewmodel which is of type List
and in your Controller Action method
and in your view which is strongly typed to OrderViewModel.
I have added a
SelectedProductIdproperty also, so you will get the user selected value from the dropdown in that Property when user post the form back to the controller.You can also use the generic
SelectListItemtype collection as your view model property to transfer the dropdown data instead of your customProductViewModelcollection.and in the GET action,
And in your view,
EDIT : As per the request from OP, edited the answer to have the Property returning static items as products
I added a get implementation to Products property to return a list of static products.
Now in your controller, you don’t need to call the GetAvailableProductsmethod as it is already there. So the controller will looks like this.
Here is the output.

If you have many items in the products, move it to a method and call that method int he get implementation instead of writing that there. That is much cleaner approach.