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

RPS picture RPS · Mar 12, 2011 · Viewed 36.9k times · Source

I have a class for MoreInfo:

public class MoreInfo
{
        public string Name { get; set; }
        public string selectedCheckboxItems {get; set;}
}

I want to know how to create a checkbox list on the view and pass the checked off items to my controller on submit.

How would I go about creating the checkbox list and how to pass all the checked items and process them?

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 12, 2011

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>