【发布时间】:2014-08-08 00:43:20
【问题描述】:
我在我的应用程序中严重依赖 EditorTemplates,但我遇到了一个我似乎无法解决的问题,而没有离开 EditorTemplates 的下拉列表。
考虑这个(视图)模型:
public class CreateStudentViewModel
{
public DropDownList StudentTypes { get; set; }
public CreateStudent Command { get; set; }
}
public class DropDownList {
public string SelectedValue { get; set; }
public IList<SelectListItem> Items { get; set; }
}
public class CreateStudent {
public string Name { get; set; }
public int StudentTypeId { get; set; }
}
我使用它为前端用户提供一种设置学生类型的方法,这是通过以下 EditorTemplate 完成的:
@model DropDownList
<div class="form-group@(Html.ValidationErrorFor(m => m.SelectedValue, " has-error"))">
@Html.LabelFor(m => m)
@Html.DropDownListFor(m => m.SelectedValue, Model.Items)
@Html.ValidationMessageFor(m => m.SelectedValue, null)
</div>
并在我看来使用:
@Html.EditorFor(m => m.StudentTypes)
现在这个 EditorTemplate 绑定到 DropDownList 上的 StudentTypes.SelectedValue,这在某些情况下很好 - 但我需要在这里将它绑定到我的 Model.Command.StudentTypeId。
我知道我可以将所有这些代码直接移动到视图并直接绑定它,而不是将其放在 EditorTemplate 中,但我会尽量避免这种情况。
理想情况下,我正在考虑扩展 EditorFor 以提供如下方式:
@Html.EditorFor(m => m.StudentTypes, new { selectedValue = Model.Command.StudentTypeId });
但我似乎无法将其翻译为:
@Html.DropDownList(@ViewBag.selectedValue.ToString(), Model.Items);
因为这只是将值 (int) 作为字段名称。欢迎任何建议! :-)
【问题讨论】:
-
根据我的经验,razor 中的 html.dropdownlist 一直很挑剔。我发现自己经常不得不将所有内容都压缩到一个复杂的视图模型中,以使其以我需要的方式绑定,尤其是对于复杂的实体。
标签: c# asp.net-mvc model-binding html.dropdownlistfor