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?
Make sure that you have trim the selected value before you assigning.
//Model
//Controller
//View
Add the Controller Section
Add the Html Section
A simple method
I know this is not really an answer to the question, but I was looking for a way to initialize the DropDownList from a list on the fly in the view when I kept stumbling upon this post.
My mistake was that I tried to create a SelectList from dictionary like this:
I then went digging in the official msdn doc, and found that
DropDownListFor
doesn't necessarily require aSelectList
, but rather anIEnumerable<SelectListItem>
:In my case I can probably also omit the
Model.Locality
as selected item, since its a) the only item and b) it already says it in theSelectListItem.Selected
property.Just in case you're wondering, the datasource is an AJAX page, that gets dynamically loaded using the SelectWoo/Select2 control.
For me was not working so worked this way:
Controller:
View:
JQuery:
When you pass a object like this:
you are saying, the Source (
Model
) and Key ("Code"
) the Text ("Name"
) and the selected value0
. Problably you do not have a0
value on your source forCode
property, so, the html helper will selected the first element. To to pass the real selectedValue to this control.For me general solution :)