CheckboxList in MVC

MVCCheckBoxList

MVCCheckBoxList is an extension for the MVC HtmlHelper class to create a POSTable checkbox list on a view, based on the data passed from the view model or defined locally.

Features

Earlier, when we need to create the checkbok list in MVC, we loop over the list of data in a model and use a checkbox within that loop.

And get the checked and unchecked data via jQuery or by using similar things.

A MVC CheckBoxlist has given us an easy way to create a checkboxlist without iterating over the list.

It creates POSTable checkboxes with the list provided from the model that is strongly typed with the model bound to the View so we do not need to use loops nor do we need to use jQuery to get the changed data any more.

How to install

Using Nuget packages we just need to use the following command in the Package Manager Console.

PM> Install-Package MvcCheckBoxList

Step 1: Open Visual Studio and select Tools >> Library Package Manager >> Package Manager Console.

liberary

The Package Manager Console window will appear as in the following:

Package Manager

Step 2: Type the command and hit Enter.

Package Manager Console

And the package is installed and added to your application.

How to use

Step 1: We need a set of data having the text and value .

For examle create a class.

  1. public class CheckboxListItems  
  2. {  
  3.    public string CheckBoxText { getset; }  
  4.    public string CheckBoxValue { getset; }  
  5. }  
Now create the list of this class in your model.
  1. public class MvcCheckBoxListModel  
  2. {  
  3.     //All the Items to be displayed in check Box List  
  4.     public List<CheckboxListItems> AvailableItems { getset; }  
  5.   
  6.     //All the Selected Items to be marked as checked  
  7.     public List<CheckboxListItems> SelectedItems { getset; }  
  8.   
  9.     //all The Items which get  checked on view  
  10.     public PostedItems PostedItem { getset; }  
  11. }  
  12. public class PostedItems  
  13. {  
  14.     public string[] ItemIds { getset; }  
  15. }  
Now intiate the model to get the data bound to the list of Available Items from the controller.

You can call a method to get the data from the database.

And pass the model to get it bound to the view.
  1. public ActionResult Index()  
  2. {  
  3.    MvcCheckBoxListModel model = new MvcCheckBoxListModel();  
  4.    return View(model);  
  5. }  
In the View write syntax as in the following:
  1. @Html.CheckBoxListFor(  
  2.    model => model.PostedItem.ItemIds,   
  3.    model => model.AvailableItems,  
  4.    item=>item.CheckBoxValue,  
  5.    item=>item.CheckBoxText,  
  6.    model=>model.SelectedItems,  
  7.    MvcCheckBoxList.Model.Position.Horizontal)  
CheckboxList in MVC

On submit you will get the selected CheckBoxIds in PostedItem.ItemIds of the Model.


Similar Articles