我读到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
移动到实际页面,那么它会起作用,它会显示复选框等。但是使用此当前设置,显示的所有内容都是角色数量的计数。
我做错了什么?
答案 0 :(得分:5)
@model MvcApplication16.Controllers.RoleViewModel
<div>
@Model.RoleName
@Html.HiddenFor(m => m.RoleId)
@Html.CheckBoxFor(m => m.InRole)
</div>
@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" }}
});
}
上面的代码工作得很好。与你的比较,看看你是否有任何不妥之处:)