CheckboxList in MVC3 View and get the checked items passed to the controller

Let’s modify your model a little:

public class ItemViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

then you could have a controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        // This action is used to render the form => 
        // we should populate our model with some values
        // which could obviously come from some data source
        var model = new[]
        {
            new ItemViewModel { Id = "1", Checked = true, Name = "item 1" },
            new ItemViewModel { Id = "2", Checked = false, Name = "item 2" },
            new ItemViewModel { Id = "3", Checked = true, Name = "item 3" },
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<ItemViewModel> items)
    {
        // This action will be invoked when the form is submitted
        // and here the view model will be properly bound and
        // you will get a collection of all items with their
        // corresponding id, name and whether they were checked or not
        ...
    }
}

then you would have a corresponding view (~/Views/Home/Index.cshtml) which would contain the form allowing the user to check/uncheck values:

@model IEnumerable<AppName.Models.ItemViewModel>
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}

and finally the editor template (~/Views/Home/EditorTemplates/ItemViewModel.cshtml):

@model AppName.Models.ItemViewModel
// Those two hidden fields are just to persist the id and name
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
<div>
    @Html.CheckBoxFor(x => x.Checked)
    @Html.LabelFor(x => x.Checked, Model.Name)
</div>

Leave a Comment

tech