CheckboxList in MVC3.0

asp.net Mvc-3

asp.net Mvc-3 Problem Overview


How can I create a checkboxList in asp.net MVC and then to handle the event with the checkboxList

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

You could have a view model:

public class MyViewModel
{
    public int Id { get; set; }
    public bool IsChecked { get; set; }
}

A controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new[] 
        {
            new MyViewModel { Id = 1, IsChecked = false },
            new MyViewModel { Id = 2, IsChecked = true },
            new MyViewModel { Id = 3, IsChecked = false },
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<MyViewModel> model)
    {
        // TODO: Handle the user selection here
        ...
    }
}

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

@model IEnumerable<AppName.Models.MyViewModel>
@{
    ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}

and the corresponding Editor template (~/Views/Home/EditorTemplates/MyViewModel.cshtml):

@model AppName.Models.MyViewModel
@Html.HiddenFor(x => x.Id)           
@Html.CheckBoxFor(x => x.IsChecked)

Now when you submit the form you would get a list of values and for each value whether it is checked or not.

Solution 2 - asp.net Mvc-3

There is even simpler way - use custom @Html.CheckBoxList() extension from here: http://www.codeproject.com/KB/user-controls/MvcCheckBoxList_Extension.aspx

Usage example (MVC3 view with Razor view engine):

@Html.CheckBoxList("NAME",                  // NAME of checkbox list
		           x => x.DataList,         // data source (list of 'DataList' in this case)
		           x => x.Id,               // field from data source to be used for checkbox VALUE
		           x => x.Name,             // field from data source to be used for checkbox TEXT
		           x => x.DataListChecked   // selected data (list of selected 'DataList' in thiscase),
		                                    // must be of same data type as source data or set to 'NULL'
		          )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionuserView Question on Stackoverflow
Solution 1 - asp.net Mvc-3Darin DimitrovView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3mikhail-tView Answer on Stackoverflow