我读到EditorTemplates是自动加载的,但是从asp.net mvc 2和现在3用剃刀,我仍然无法让它工作.
我的模型看起来像这样:
public class Role@R_301_93@l { public int RoleId { get; set; } public bool InRole { get; set; } public string RoleName { get; set; } } public class User@R_301_93@l { public User User { get; set; } public IEnumerable<Role@R_301_93@l> Roles { get; set; } }
我的观点如下:
〜/查看/角色/ Edit.cshtml
@model Project.Web.@R_301_93@l.User@R_301_93@l @using (Html.BeginForm()) { @Html.EditorFor(model => model.Roles) <!-- Other stuff here --> }
〜/查看/角色/ EditorTemplates / Role@R_301_93@l.cshtml
@model Project.Web.@R_301_93@l.Role@R_301_93@l @foreach (var i in Model) { <div> @i.RoleName @Html.HiddenFor(model => i.RoleId) @Html.CheckBoxFor(model => i.InRole) </div> }
如果我将内容从EditorTemplate移动到实际页面,那么它可以工作,它会显示复选框等.但是使用当前设置,显示的所有内容都是角色数量的计数.
我究竟做错了什么?
解决方法
〜/查看/角色/ EditorTemplates / Role@R_301_93@l.cshtml
@model MvcApplication16.Controllers.Role@R_301_93@l <div> @Model.RoleName @Html.HiddenFor(m => m.RoleId) @Html.CheckBoxFor(m => m.InRole) </div>
〜/查看/角色/ Edit.cshtml
@model MvcApplication16.Controllers.User@R_301_93@l @using (Html.BeginForm()) { @Html.EditorFor(m => m.Roles) <!-- Other stuff here --> }
楷模
public class User@R_301_93@l { public User User { get; set; } public IEnumerable<Role@R_301_93@l> Roles { get; set; } } public class Role@R_301_93@l { 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 User@R_301_93@l() { User = new User() { Name = "Test" },Roles = new List<Role@R_301_93@l>() { new Role@R_301_93@l() { RoleId = 1,InRole = true,RoleName = "Test Role" }} }); }
上面的代码工作得很好.与你的比较,看看你有没有看到任何问题:)