Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC CheckBoxList from model with List Property

Apologies if the title is unclear.

I'm trying to return my model from a form submit in ASP.NET MVC.

My question is nearly the same as this question, only differing in that I don't have a List<Model> but a model like:

public Model
{
     string UserName {get; set;}
     string Password {get; set;}
     List<Roles> UserRoles {get; set;}
}

where I need the UserRoles as checkboxes that the admin can select from when creating a new user. My question is, I'm unsure how to use a '@Html.CheckBoxFor' against a list. I tried this:

 @for (var i = 0; i < Model.UserRoles.Count();i++ )
 {
   @Html.HiddenFor(model => model.UserRoles[i].RoleID)
   @Html.CheckBoxFor(model => model.UserRoles[i].Selected)
   @Html.LabelFor(model => model.UserRoles[i].Name)
 }

which in no way worked - every label on the page is "Name", and my List was empty in the POST. Can anyone offer me any guidance on this?

like image 584
Jonesopolis Avatar asked Dec 19 '13 16:12

Jonesopolis


3 Answers

No need to go away from Razor at all.

This works for me:

for (var i = 0; i < Model.UserRoles.Count(); i++)
{
    var role = Model.UserRoles[i];
    @Html.HiddenFor(model => model.UserRoles[i].RoleId)
    @Html.CheckBoxFor(model => model.UserRoles[i].Selected)
    @Html.LabelFor(model=> model.UserRoles[i].Name, role.Name)
}
like image 155
LiverpoolsNumber9 Avatar answered Nov 18 '22 10:11

LiverpoolsNumber9


See below code, this way you don't need to hide the role Id, also when you save the selected roles for the user, you don't need to loop through all roles to see which role is selected.

View

@foreach (Roles info in Model.UserRoles)
{
    <span>
        <input type="checkbox" class="checkbox" name="selectedRoles" value="@info.RoleName" id="@infoRoleName" />
        <label for="@info.RoleName">@info.RoleName</label>
    </span>
}

Action

[HttpPost]
public ActionResult CreateUsers(Model model, string[] selectedRoles)
{
       //
}
like image 21
Lin Avatar answered Nov 18 '22 12:11

Lin


From your code in the view, the post should work fine providing your post action looks like this:

[HttpPost]
public ActionResult Action(Model model)
{
    return View(model);
}

i.e. passing your model across as the argument.

Also make sure you have your model reference in the view too:

@model YourNameSpace.Model
like image 1
hutchonoid Avatar answered Nov 18 '22 11:11

hutchonoid