我读到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移动到实际页面,那么它可以工作,它会显示复选框等.但是使用当前设置,显示的所有内容都是角色数量的计数.
我究竟做错了什么?
解决方法
〜/查看/角色/ 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" }} }); }
上面的代码工作得很好.与你的比较,看看你有没有看到任何问题:)