简体   繁体   English

当在EditorFor模板中移动时,DropDownListFor不会绑定到值

[英]DropDownListFor doesn't bind to value when moved inside EditorFor template

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. 其中Model.CountryOptions是预Model.CountryOptionsIEnumerable<SelectListItem> ,并且在主模板中一切正常。

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: 在EditorTemplates / DropDownList.cshtml中,我具有:

<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? 这是怎么回事?

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 SelectListItem s. 我不知道这是一个错误还是仅是设计使然 ,但是从编辑器模板调用DropDownList时,设置初始选定项的唯一方法是在SelectListItem之一上设置Selected属性。

My suggested fix is, when you set Model.CountryOptions make sure the default option is selected. 我建议的解决方法是,在设置Model.CountryOptions时,请确保已选择默认选项。

You have to explicitly set the selected object when passing in the SelectList something like the one below. 在传递SelectList时,您必须显式设置所选对象,如下所示。 If your CountryOption is a list this should work. 如果您的CountryOption是列表,则应该可以使用。

@Html.EditorFor(x => x.CountryId, "DropDownList", new { options = new SelectList(Model.CountryOptions, Model.CountryID), optionLabel = "Please select" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM