![](/img/trans.png)
[英]DropDownListFor in the context of a list of child models doesn't bind value
[英]DropDownListFor doesn't bind to value when moved inside EditorFor template
我正在尝试将类似的内容移动到编辑器模板中:
<div class="field">
@Html.ValidationMessageFor(x => x.CountryId)
@Html.LabelFor(x => x.CountryId)
@Html.DropDownListFor(x => x, Model.CountryOptions, "Please select")
</div>
其中Model.CountryOptions
是预Model.CountryOptions
的IEnumerable<SelectListItem>
,并且在主模板中一切正常。
因此,我将以上内容替换为:
@Html.EditorFor(x => x.CountryId, "DropDownList", new { options = Model.CountryOptions, optionLabel = "Please select" })
在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>
所有这些看起来都与以前相同,并且在发布时可以正确绑定到模型,但是现在在初始加载时,下拉列表中没有将任何现有值标记为已选择。
这是怎么回事?
我不知道这是一个错误还是仅是设计使然 ,但是从编辑器模板调用DropDownList时,设置初始选定项的唯一方法是在SelectListItem之一上设置Selected属性。
我建议的解决方法是,在设置Model.CountryOptions
时,请确保已选择默认选项。
在传递SelectList时,您必须显式设置所选对象,如下所示。 如果您的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.