Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 How To Bind Multiple Checkboxes to 1 Property in ViewModel

I need to display a list of checkboxes, which more than one can be checked.

When the user hits submit, the value of these checkboxes need to go into a property in the ViewModel...this is what I got so far...

public class RegisterModel
{
    public List<string> Roles { get; set; }
    public List<RoleModel> SelectedRoles { get; set; }    
}
public class RoleModel
{
    public string RoleName { get; set; }
}

In the view I am trying to do this...

@foreach (var role in Model.Roles)
{
    @Html.CheckBoxFor(m => m.SelectedRoles, role.RoleName)@role.RoleName
}

I get the following error:

CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'bool'

Can someone tell me what I'm doing wrong?

like image 863
thiag0 Avatar asked Nov 02 '11 20:11

thiag0


1 Answers

Simple: adapt your view models to match your views requirement (which is to show a list of checkboxes for some roles), use editor templates and avoid writing loops in your views.

So:

View model:

public class RegisterModel
{
    public List<RoleModel> Roles { get; set; }
}

public class RoleModel
{
    public string RoleName { get; set; }
    public bool Selected { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new RegisterModel
        {
            Roles = new[]
            {
                new RoleModel { RoleName = "administrator" },
                new RoleModel { RoleName = "developer" },
                new RoleModel { RoleName = "janitor :-)" },
            }.ToList()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(RegisterModel model)
    {
        // at this stage the model will contain all the 
        // information you need
        return View(model);
    }
}

View (~/Views/Home/Index.cshtml):

@model RegisterModel

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Roles)
    <button type="submit">OK</button>
}

Editor template (~/Views/Home/EditorTemplates/RoleModel.cshtml):

@model RoleModel

<div>
    @Html.HiddenFor(x => x.RoleName)
    @Html.CheckBoxFor(x => x.Selected)
    @Html.LabelFor(x => x.Selected, Model.RoleName)
</div>
like image 61
Darin Dimitrov Avatar answered Jan 05 '23 09:01

Darin Dimitrov