如何使用asp.net mvc EditorTemplate

时间:2011-01-12 16:58:07

标签: asp.net-mvc asp.net-mvc-3

我读到EditorTemplates是自动加载的,但是从asp.net mvc 2和现在3用剃刀,我仍然无法使用它。

我的模型看起来像这样:

public class RoleViewModel
{
    public int RoleId { get; set; }
    public bool InRole { get; set; }
    public string RoleName { get; set; }
}

public class UserViewModel
{
    public User User { get; set; }
    public IEnumerable<RoleViewModel> Roles { get; set; }
}

我的观点如下:

〜/查看/角色/ Edit.cshtml

@model Project.Web.ViewModel.UserViewModel
@using (Html.BeginForm()) {
   @Html.EditorFor(model => model.Roles)
   <!-- Other stuff here -->
}

〜/查看/角色/ EditorTemplates / RoleViewModel.cshtml

@model Project.Web.ViewModel.RoleViewModel
@foreach (var i in Model)
{
    <div>
    @i.RoleName
    @Html.HiddenFor(model => i.RoleId)
    @Html.CheckBoxFor(model => i.InRole)
    </div>
}

如果我将内容从EditorTemplate移动到实际页面,那么它会起作用,它会显示复选框等。但是使用此当前设置,显示的所有内容都是角色数量的计数。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

〜/查看/角色/ EditorTemplates / RoleViewModel.cshtml

@model MvcApplication16.Controllers.RoleViewModel
<div>
    @Model.RoleName
    @Html.HiddenFor(m => m.RoleId)
    @Html.CheckBoxFor(m => m.InRole)
</div>

〜/查看/角色/ Edit.cshtml

@model MvcApplication16.Controllers.UserViewModel
@using (Html.BeginForm()) {
   @Html.EditorFor(m => m.Roles)
   <!-- Other stuff here -->
}

模型

public class UserViewModel {
    public User User { get; set; }
    public IEnumerable<RoleViewModel> Roles { get; set; }
}

public class RoleViewModel {
    public int RoleId { get; set; }
    public bool InRole { get; set; }
    public string RoleName { get; set; }
}

public class User {
    public string Name { get; set; }
}

控制器

public ActionResult Edit() {
    return View(
        new UserViewModel() {
            User = new User() { Name = "Test" },
            Roles = new List<RoleViewModel>() { 
                new RoleViewModel() { 
                    RoleId = 1, 
                    InRole = true, 
                    RoleName = "Test Role" }}
        });
}

上面的代码工作得很好。与你的比较,看看你是否有任何不妥之处:)