Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET
Tip/Trick

How to Use CheckBoxListFor With ASP.NET MVC 4?

Rate me:
Please Sign up or sign in to vote.
4.87/5 (19 votes)
8 Jul 2013CPOL2 min read 259.6K   22   35
Here I explain about a nice and cool CheckBoxListFor Plugin

Introduction

  • One of the cool features of Microsoft MVC web development framework since its inception was its rich HTML helpers library
  • It provided helpers to create most common HTML controls like text boxes, drop down lists, text areas, etc.
  • But there is No HTML helper extension for creation of a checkbox lists
  • No such extension for latest .NET Framework 4.5 (MVC 4) also
  • So, here I am explaining a nice and cool plugin, which fills that missing MVC HtmlHelper
  • I have written a blog post about this. It's here (with the source code)

What is it?

  • It is a custom extension of Microsoft MVC Framework's HtmlHelper class, which creates a POSTable Model-based list of check boxes
  • It was created because there is no built-in MVC way to do this at all (including MVC4)

What are the Features of CheckBoxListFor Plugin ?

  • Easy to use
  • Creates POSTable check boxes from any set of data
  • Strongly-typed, based on View Model
  • Extensive control over layout and appearance
  • Right-to-left language support (e.g. for Arabic, Hebrew, etc.)
  • It's Free (Open source)

How to Use CheckBoxListFor with ASP.NET MVC 4 ?

  • Here, I have used Visual Studio 2012 and ASP.NET MVC 4 Web Application
  • Please follow the inline comments for better understanding

Step 1: How to Install CheckBoxListFor Plugin?

Tools ==> Library Package Manger ==> Package Manager Console

Image 1

  • Type Install-Package MvcCheckBoxList and press Enter.
  • Image 2

  • When it's Successful:
  • Image 3

  • After that, you could see that it adds MvcCheckBoxList assembly into your project.
  • Image 4

Step 2: Create Class 'Fruit'

Fruit.cs

C#
namespace CheckBoxListForApp.Models
{
 /// <summary>
 /// model for Fruit
 /// </summary>
 public class Fruit
 {
  //Integer value of a checkbox
  public int Id { get;set;}

  //String name of a checkbox
  public string Name { get;set; }

  //Boolean value to select a checkbox
  //on the list
  public bool IsSelected{get;set;}

  //Object of html tags to be applied
  //to checkbox, e.g.:'new{tagName = "tagValue"}'
  public object Tags { get;set;}

 }
}

Step 3: Create 'FruitViewModel' View Model

FruitViewModel.cs

C#
using System.Collections.Generic;

namespace CheckBoxListForApp.Models
{
    /// <summary>
    /// for View Model of FruitViewModel
    /// </summary>
    public class FruitViewModel
    {
        public IEnumerable<Fruit> AvailableFruits { get; set; }
        public IEnumerable<Fruit> SelectedFruits { get; set; }
        public PostedFruits PostedFruits { get; set; }
    }
}

Step 4: Create 'PostedFruits' Helper class to make posting back selected values easier

PostedFruits.cs

C#
namespace CheckBoxListForApp.Models
{
    /// <summary>
    /// for Helper class to make posting back selected values easier
    /// </summary>
    public class PostedFruits
    {
        //this array will be used to POST values from the form to the controller
        public string[] FruitIds { get; set; }
    }
}

Step 5 'HomeController' looks like below

HomeController.cs

C#
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using CheckBoxListForApp.Models;

namespace CheckBoxListForApp.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// for get all fruits
        /// </summary>
        [HttpGet]
        public ActionResult Index()
        {
            return View(GetFruitsInitialModel());
        }

        /// <summary>
        /// for post user selected fruits
        /// </summary>
        [HttpPost]
        public ActionResult Index(PostedFruits postedFruits)
        {
            return View(GetFruitsModel(postedFruits));
        }

        /// <summary>
        /// for setup view model, after post the user selected fruits data
        /// </summary>
        private FruitViewModel GetFruitsModel(PostedFruits postedFruits)
        {
            // setup properties
            var model = new FruitViewModel();
            var selectedFruits = new List<Fruit>();
            var postedFruitIds = new string[0];
            if (postedFruits == null) postedFruits = new PostedFruits();

            // if a view model array of posted fruits ids exists
            // and is not empty,save selected ids
            if (postedFruits.FruitIds != null && postedFruits.FruitIds.Any())
            {
                postedFruitIds = postedFruits.FruitIds;
            }

            // if there are any selected ids saved, create a list of fruits
            if (postedFruitIds.Any())
            {
              selectedFruits = FruitRepository.GetAll()
               .Where(x => postedFruitIds.Any(s => x.Id.ToString().Equals(s)))
               .ToList();
            }

            //setup a view model
            model.AvailableFruits = FruitRepository.GetAll().ToList();
            model.SelectedFruits = selectedFruits;
            model.PostedFruits = postedFruits;
            return model;
        }

        /// <summary>
        /// for setup initial view model for all fruits
        /// </summary>
        private FruitViewModel GetFruitsInitialModel()
        {
            //setup properties
            var model = new FruitViewModel();
            var selectedFruits = new List<Fruit>();

            //setup a view model
            model.AvailableFruits = FruitRepository.GetAll().ToList();
            model.SelectedFruits = selectedFruits;
            return model;
        }
    }
}

Step 6: Create Data Retrieval Repository as 'FruitRepository'

FruitRepository.cs

C#
using System.Collections.Generic;
using System.Linq;

namespace CheckBoxListForApp.Models
{
    /// <summary>
    /// work as fruit repository
    /// </summary>
    public static class FruitRepository
    {
        /// <summary>
        /// for get fruit for specific id
        /// </summary>
        public static Fruit Get(int id)
        {
            return GetAll().FirstOrDefault(x => x.Id.Equals(id));
        }

        /// <summary>
        /// for get all fruits
        /// </summary>
        public static IEnumerable<Fruit> GetAll()
        {
            return new List<Fruit> {
                              new Fruit {Name = "Apple", Id = 1 },
                              new Fruit {Name = "Banana", Id = 2},
                              new Fruit {Name = "Cherry", Id = 3},
                              new Fruit {Name = "Pineapple", Id = 4},
                              new Fruit {Name = "Grape", Id = 5},
                              new Fruit {Name = "Guava", Id = 6},
                              new Fruit {Name = "Mango", Id = 7}
                            };
        }
    }
}

Step 7: View Page is as below

Index.cshtml

XML
@using MvcCheckBoxList.Model
@model CheckBoxListForApp.Models.FruitViewModel

@{
    ViewBag.Title = "Home Page";
}

<section class="checkBoxListFor">
    <p>
        <label>Please Select Fruits:</label>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
            @Html.CheckBoxListFor(model => model.PostedFruits.FruitIds,
                                  model => model.AvailableFruits,
                                  fruit => fruit.Id,
                                  fruit => fruit.Name,
                                  model => model.SelectedFruits,
                                  Position.Horizontal)
            <input class="green" type="submit" 
                      value="POST to Controller" />
        }
    </p>
</section>

Note: You saw that you have to add reference to the 'MvcCheckBoxList.Model' as above.

Step 8: When you Run the Application

  • When Page loads for the First Time:
  • Image 5

  • When you Post the Page:
  • Image 6

That's it. You're done.

Conclusion

  • In this tip, I have shown the basic usage of CheckBoxListFor
  • There are number of overload methods that exist for this extension
  • So if you need to learn all of them, you have to browse the below mentioned URL
  • Some of them are, can change Orientation (Horizontal/Vertical), can use Custom Layouts,Templates and much much more ....
  • So enjoy with this Great Missing MVC Extension

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Freelancer
Sri Lanka Sri Lanka
Sampath Lokuge holds a Bachelor of Science degree in the Mathematics and Computer Science at the University of Colombo, Sri Lanka.

He possesses over 8 years of experience in constructing web applications using Microsoft Technologies including ASP.net MVC, C#, SQL Server, Web API, Entity Framework and also other web technologies such as HTML5, CSS3,jQuery and AngularJS.

Sampath has earned Microsoft certifications such as MCP, MCAD, MCSD and MCTS and very recently he has completed MS (Microsoft Specialist) for MVC 4 and MCSD (Windows Store Apps Using HTML5).

Besides that, he is an active blogger, writing about web and mobile development issues and promoting best practices.He also actively participates in online communities such as Code Project and StackOverflow.He himself is handling three communities, which are ASP.net MVC 5 With C# on Linkedin,Entity Framework 6 on G+ and Hybrid Mobile App with WinJS on Facebook.

Now, I am a 100% Freelancer. Smile | :)

Tech Blogs


Sampath Lokuge Tech Universe

Communities which I'm Handling :


Entity Framework 6

ASP.net MVC 5 With C#

Hybrid Mobile App with WinJS

Comments and Discussions

 
QuestionCan We Separate Checkbox and Label Pin
Member 111466187-Mar-19 0:09
Member 111466187-Mar-19 0:09 
QuestionHow to get value of checkbox from checkboxlistFor using jquery ajax in MVC Pin
Member 131274683-Jul-17 19:43
Member 131274683-Jul-17 19:43 
QuestionPackage Installation Error Pin
Patee Gutee17-Aug-16 4:15
Patee Gutee17-Aug-16 4:15 
AnswerRe: Package Installation Error Pin
Sampath Lokuge17-Aug-16 4:31
Sampath Lokuge17-Aug-16 4:31 
QuestionStyles in CheckBoxListFor Pin
Member 122612377-Jun-16 23:40
Member 122612377-Jun-16 23:40 
QuestionQuestion Pin
Member 120363889-Oct-15 0:34
Member 120363889-Oct-15 0:34 
QuestionQuery Pin
GopiNath Tharra21-Apr-15 2:13
GopiNath Tharra21-Apr-15 2:13 
QuestionID keeps changing on postback Pin
Chris Randle16-Apr-15 2:53
professionalChris Randle16-Apr-15 2:53 
QuestionValidation Pin
Member 976762616-Apr-15 2:32
Member 976762616-Apr-15 2:32 
Questioni have a small correction Pin
vamsilatha6-Apr-15 7:11
professionalvamsilatha6-Apr-15 7:11 
AnswerRe: i have a small correction Pin
GopiNath Tharra21-Apr-15 2:26
GopiNath Tharra21-Apr-15 2:26 
GeneralMy vote of 1 Pin
Member 110919351-Oct-14 5:17
Member 110919351-Oct-14 5:17 
GeneralRe: My vote of 1 Pin
Sampath Lokuge1-Oct-14 7:25
Sampath Lokuge1-Oct-14 7:25 
QuestionList of Listboxes :) Pin
Borrierulez19-Mar-14 2:28
Borrierulez19-Mar-14 2:28 
AnswerRe: List of Listboxes :) Pin
Sampath Lokuge19-Mar-14 3:51
Sampath Lokuge19-Mar-14 3:51 
AnswerRe: List of Listboxes :) Pin
Borrierulez19-Mar-14 7:36
Borrierulez19-Mar-14 7:36 
GeneralRe: List of Listboxes :) Pin
Sampath Lokuge19-Mar-14 19:42
Sampath Lokuge19-Mar-14 19:42 
GeneralRe: List of Listboxes :) Pin
Borrierulez24-Mar-14 3:47
Borrierulez24-Mar-14 3:47 
GeneralRe: List of Listboxes :) Pin
Sampath Lokuge24-Mar-14 11:17
Sampath Lokuge24-Mar-14 11:17 
GeneralRe: List of Listboxes :) Pin
Borrierulez9-Apr-14 5:35
Borrierulez9-Apr-14 5:35 
GeneralRe: List of Listboxes :) Pin
Sampath Lokuge10-Apr-14 0:51
Sampath Lokuge10-Apr-14 0:51 
QuestionLinq statement with .ToString() Pin
Corn Fed3-Dec-13 5:11
Corn Fed3-Dec-13 5:11 
AnswerRe: Linq statement with .ToString() Pin
Sampath Lokuge3-Dec-13 19:47
Sampath Lokuge3-Dec-13 19:47 
QuestionHow to implement select all function in it Pin
manish2kk18-Nov-13 7:31
manish2kk18-Nov-13 7:31 
AnswerRe: How to implement select all function in it Pin
Sampath Lokuge19-Nov-13 1:26
Sampath Lokuge19-Nov-13 1:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.