@Html.EditorForModel()下拉菜单



我正在处理MVC4using @Html.EditorForModel(),它将dropdownlist显示为文本框,我想通过设置任何attribute和覆盖模板来显示Dropdown列表。请与我分享MVC4示例。

@model Models.Employee
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Employee</legend>
        @Html.EditorForModel()
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

提前谢谢。

您可以定义一个表示下拉列表的视图模型:

public class ItemsViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

将在您的主视图模型中使用:

public class MyViewModel
{
    public ItemsViewModel DropDown1 { get; set; }
    public ItemsViewModel DropDown2 { get; set; }
    ...
}

现在剩下的就是为ItemsViewModel编写一个自定义编辑器模板,该模板应该放在~/Views/Shared/EditorTemplates/ItemsViewModel.cshtml中。请注意,模板的名称和位置很重要:

@model ItemViewModel
@Html.DropDownListFor(x => x.SelectedValue, Model.Values)

这几乎就是它所需要的全部。

覆盖模板是必需的吗?您可以使用@Html.DropDownList()帮助程序。

有一个关于如何在asp.net网站中使用的完整示例,您可以下载该项目:此处

最新更新