I’m trying to set the selected Value for a drop down list.
In Controller I have
ViewData["productType"] = new SelectList(myDropDownList);
And in the View:
<%= Html.DropDownList("productType", ViewData["productType"] as SelectList, "defaultValue")%>
So far So good, but the problem is that now I have “defaultValue” twice in my drop down list. so I have all my values in dropdownlist including the “defaultValue”. but this code will add the “defaultValue” as the first element. and I see two samples of it.
I like to set the selected valiue to “defaultValue” without adding it twice.
I tried
ViewData["productType"] = new SelectList(myDropDownList, "defaultValue" );
but it didn’t work.
Can anyone please tell me what to do?
You should not be using the same name as first argument for the dropdown as the second one. In your example you have used
productTypefor storing both the selected value and the list of available values. In order to render a DropDown in ASP.NET MVC you need 2 properties:and inside your controller action you could set those 2 properties:
this assumes that you already have an element with
value="abc"inside your dropdown list of product types. The value will then be automatically preselected.I would recommend you an alternative approach though for rendering dropdown lists. It consists of getting rid of view data and introducing view models and using the strongly typed version of the helper:
then you will have a controller action that will populate this view model and pass it to the view:
and finally inside your strongly typed view: