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.
The Package Manager Console window will appear as in the following:
Step 2: Type the command and hit Enter.
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.
- public class CheckboxListItems
- {
- public string CheckBoxText { get; set; }
- public string CheckBoxValue { get; set; }
- }
Now create the list of this class in your model.
- public class MvcCheckBoxListModel
- {
-
- public List<CheckboxListItems> AvailableItems { get; set; }
-
-
- public List<CheckboxListItems> SelectedItems { get; set; }
-
-
- public PostedItems PostedItem { get; set; }
- }
- public class PostedItems
- {
- public string[] ItemIds { get; set; }
- }
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.
- public ActionResult Index()
- {
- MvcCheckBoxListModel model = new MvcCheckBoxListModel();
- return View(model);
- }
In the View write syntax as in the following:
- @Html.CheckBoxListFor(
- model => model.PostedItem.ItemIds,
- model => model.AvailableItems,
- item=>item.CheckBoxValue,
- item=>item.CheckBoxText,
- model=>model.SelectedItems,
- MvcCheckBoxList.Model.Position.Horizontal)
On submit you will get the selected CheckBoxIds in PostedItem.ItemIds of the Model.