How can I set the selected value of a Html.DropDownListFor? I've been having a look online and have seen that it can be achieved by using the fourth parameter so like the below:
@Html.DropDownListFor(m => m, new SelectList(Model, "Code", "Name", 0), "Please select a country")
My select list then display like this:
<select id="ShipFromCountries" name="ShipFromCountries">
<option value="">Please select a country</option>
<option value="GB">United Kingdom</option>
<option value="US">United States</option>
...
</select>
But for some reason United Kingdom remains selected but I want "Please select a country" to be selected.
Anyone know how I can achieve this?
EDIT
I've updated my code as there was a slight change in functionality however still seem to be encountering this problem. This is what is in my view:
@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
1
is the Id of the option
that I want selected, I have also tried with the text of the option
but that also does not work.
Any ideas?
I had a similar issue, I was using the ViewBag and Element name as same. (Typing mistake)
Your code has some conceptual issues:
First,
When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a
SelectedOrderId
as part of your model or something like that, in order to use it in this way:Second,
Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.
Some code I would use if I were you to avoid this issues and write better MVC code:
Viewmodel:
Controller:
In your View:
Linq to Dropdown with empty item, selected item (works 100%)
(Strongly Typed,Chances for error minimum) Any model changes will be reflected in the binding
Controller
View
This method for binding data also possible
You should forget the class
Use this in your Controller:
Select the value:
Add the list to the ViewData:
Use this in your View:
-
More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
If you know what will be in the view, you can also set the default value from Controller as well rather then set up it into the view/cshtml file. No need to set default value from HTML side.
In the Controller file.
In the .cshtml file.
You need to get one and set different one. Selected value can not be the same item that you are about to set.
I use Enum dictionary for my list, that's why there is "key", "value" pair.