How to use asp.net mvc EditorTemplate

I read that EditorTemplates load automatically, but from asp.net mvc 2 and now 3 with a razor, I still can't get this to work.

My model looks like this:

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; } } 

My view is as follows:

~ / Views / Roles / Edit.cshtml

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

~ / Views / Roles / 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> } 

If I move the content from the EditorTemplate to the actual page, then it works, it shows a checkbox, etc. But with this current setting, all that is displayed is the number of roles.

What am I doing wrong?

+7
source share
1 answer

~ / Views / Roles / EditorTemplates / RoleViewModel.cshtml

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

~ / Views / Roles / Edit.cshtml

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

Models

 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; } } 

controller

 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" }} }); } 

The above code works fine. Compare this with yours and see if you see something wrong :)

+5
source

All Articles