C# DropDownListFor不';在EditorFor模板内移动时,不能绑定到值

C# DropDownListFor不';在EditorFor模板内移动时,不能绑定到值,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我正在尝试将类似的内容移动到编辑器模板中: <div class="field"> @Html.ValidationMessageFor(x => x.CountryId) @Html.LabelFor(x => x.CountryId) @Html.DropDownListFor(x => x, Model.CountryOptions, "Please select") </div> 在EditorTemplates/Dro

我正在尝试将类似的内容移动到编辑器模板中:

<div class="field">
    @Html.ValidationMessageFor(x => x.CountryId)
    @Html.LabelFor(x => x.CountryId)
    @Html.DropDownListFor(x => x, Model.CountryOptions, "Please select")
</div>
在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>

@Html.ValidationMessageFor(x=>x)
@LabelFor(x=>x)
@(x=>x,(IEnumerable)视图数据[“选项”],(字符串)视图数据[“选项标签”])
这一切看起来与以前一样,并在过帐时正确绑定到模型,但现在任何现有值都不会在初始加载时的下拉列表中标记为选中


发生了什么?

我不知道这是一个bug还是仅仅是出于设计,但当从编辑器模板调用DropDownList时,设置初始选定项的唯一方法是在其中一个SelectListItems上设置selected属性


我建议的解决方法是,当您设置
模型时。CountryOptions
确保选择了默认选项。

您必须在传入SelectList时显式设置所选对象,如下图所示。如果您的CountryOption是一个列表,那么它应该可以工作

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

但是,如果绑定到模板模型类型的子属性,例如,
@Html.EditorFor(x=>x.Address)
和包含
@Html.DropDownListFor(x=>x.CountryId)
@stovroz的EditorTemplates/Address.cshtml,则即使在编辑器模板中,它也能正确设置它,当前名称是空字符串(当您执行
DropDownListFor(x=>x)
DropDownList(“”
)时)。当它不起作用时就是这种情况,但对子属性起作用。请参阅源代码。
@Html.EditorFor(x => x.CountryId, "DropDownList", new { options = new SelectList(Model.CountryOptions, Model.CountryID), optionLabel = "Please select" })