为了生成一个下拉列表,您需要在视图模型上使用 2 个属性:一个用于将选定值绑定到的标量属性和一个包含要在下拉列表中显示的项目的集合属性。
所以你可以定义一个视图模型:
public class DropDownListViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
然后在您的主视图模型上具有这种类型的属性:
public DropDownListViewModel Foo { get; set; }
现在您可以为这种类型创建一个自定义编辑器模板 (~/Views/Shared/EditorTemplates/DropDownListViewModel.ascx):
<%@ Control
Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DropDownListViewModel>"
%>
<%= Html.DropDownListFor(x => x.SelectedValue, Model.Items) %>
然后在你的主视图中:
<%= Html.EditorFor(x => x.Foo) %>
现在剩下的就是让你的控制器动作渲染主视图,用相应的值填充Foo 属性。可以是硬编码的,来自存储库或其他任何东西。没关系。
另一方面,如果您事先知道这些值,您可以在编辑器模板 (~/Views/Shared/EditorTemplates/YesNoDropDown.ascx) 中对它们进行硬编码:
<%= Html.DropDownList(
"",
new SelectList(
new[]
{
new { Value = "true", Text = "Yes" },
new { Value = "false", Text = "No" },
},
"Value",
"Text",
Model
)
) %>
然后:
<%= Html.EditorFor(x => x.IsActive, "YesNoDropDown") %>
或通过装饰视图模型上的 IsActive 属性:
[UIHint("YesNoDropDown")]
public bool IsActive { get; set; }
然后:
<%= Html.EditorFor(x => x.IsActive) %>