@ Html.EditorForModel()下拉列表

时间:2013-07-20 08:21:54

标签: asp.net html5 asp.net-mvc-4 razor

我正在处理 MVC4 using @Html.EditorForModel(),它正在显示dropdownlist作为文本框,我想通过设置Dropdown来显示attribute列表1}}和覆盖模板。请与我分享 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")
}

提前致谢。

2 个答案:

答案 0 :(得分:4)

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

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)

这就是它所需要的一切。

答案 1 :(得分:-1)

这是最重要的模板必备品吗?您可以使用@Html.DropDownList()帮助程序。

有关如何在asp.net网站上使用的完整示例,您可以下载该项目:Here