Reputation: 7065
I'm trying to move the likes of this into an editor template:
<div class="field">
@Html.ValidationMessageFor(x => x.CountryId)
@Html.LabelFor(x => x.CountryId)
@Html.DropDownListFor(x => x, Model.CountryOptions, "Please select")
</div>
Where Model.CountryOptions
is a prefilled IEnumerable<SelectListItem>
, and everything works perfectly while in the main template.
So, I replace the above with:
@Html.EditorFor(x => x.CountryId, "DropDownList", new { options = Model.CountryOptions, optionLabel = "Please select" })
and inside EditorTemplates/DropDownList.cshtml I have:
<div class="field">
@Html.ValidationMessageFor(x => x)
@Html.LabelFor(x => x)
@Html.DropDownListFor(x => x, (IEnumerable<SelectListItem>)ViewData["options"], (string)ViewData["optionLabel"])
</div>
This all appears the same as before and binds to the model correctly on posting, but now any existing value is not being marked as selected in the drop down list on initial load.
What's going on?
Upvotes: 1
Views: 518
Reputation: 505
You have to explicitly set the selected object when passing in the SelectList something like the one below. If your CountryOption is a list this should work.
@Html.EditorFor(x => x.CountryId, "DropDownList", new { options = new SelectList(Model.CountryOptions, Model.CountryID), optionLabel = "Please select" })
Upvotes: 1
Reputation: 28608
I don't know if this is a bug or simply by design, but when calling DropDownList from the editor template, the only way to set the initial selected item is by setting the Selected property on one of the SelectListItems.
My suggested fix is, when you set Model.CountryOptions
make sure the default option is selected.
Upvotes: 1