In an EditorFor view in MVC with Razor markup, if you do this:
@Html.TextBox("")
The HTML comes out with the correct input name for the model, like so:
<input id="usr_Roles" name="usr.Roles" type="text" value="">
The “usr.Roles” name comes from this EditorFor line:
@Html.EditorFor(modelItem => usr.Roles, "RoleList")
Unfortunately, I’m trying to generate a set of checkboxes with the name “usr.Roles”. Because of the way MVC renders checkboxes, I can’t use Html.Checkbox. I can generate them manually like so:
@foreach (string roleName in Roles.GetAllRoles())
{
string checkboxId = "checkbox_" + roleName;
<input type="checkbox" name="usr.Roles" id="@checkboxId" value="@roleName" @Html.Raw(Model.Contains(roleName) ? "checked" : "") />
<label for="@checkboxId">@roleName</label>
}
The above works, but only because I manually specify “usr.Roles” as the checkbox name.
My question is this: Where in the maze of objects and properties does the @Html.TextBox object find the “usr.Roles” “usr-Roles” strings? And can I find it myself and use it in the checkboxes?
I don’t know why on earth you would be wanting to manually generate ids and names of your checkboxes instead of simply using the
Html.CheckBoxForhelper which does all this for you, but in case you have some reasons, here’s how:Obviously that’s shown here pure for some educational purposes. I would really avoid such monstrosity and simply use Html helpers and editor templates. Another thing that shocks me in your view is the following line of code:
Roles.GetAllRoles(). It’s as if your view is querying data. That’s last thing a view should do. It’s the controller’s responsibility to query data, fill a view model and pass this view model to the view so that it simply shows the data.So let’s try to elaborate your example. From what I can understand you are trying to show a list of checkboxes for each role so that the user can select them.
As always you start with a view model expressing your views requirements:
then you write a controller action which will query your data and fill the view model:
then you will have a
Index.cshtmlview:and a corresponding editor template which will be rendered for each element of the Roles collection (
~/View/Shared/EditorTemplates/RoleViewModel.cshtml):No more
foreachloops in the views, no more ugly hacks with names and ids, no more data pulling from the views.