Click here to Skip to main content
Click here to Skip to main content

Tagged as

How to Use CheckBoxListFor With ASP.NET MVC 4?

, 8 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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

  • Type Install-Package MvcCheckBoxList and press Enter.

  • When it's Successful:
  • After that, you could see that it adds MvcCheckBoxList assembly into your project.

Step 2: Create Class 'Fruit'

Fruit.cs

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

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

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

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

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

@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:
  • When you Post the Page:

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)

Share

About the Author

Sampath Lokuge
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 7 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 | :)
 
My oDesk Profile : oDesk
 
My Elance Profile : Elance
 
My Email : sugeesampathlokuge@gmail.com

My Tech Blog

Sampath Lokuge Tech Blog

Communities which I'm Handling :

Entity Framework 6
 
ASP.net MVC 5 With C#
 
Hybrid Mobile App with WinJS
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 1 PinmemberMember 110919351-Oct-14 6:17 
GeneralRe: My vote of 1 PinmemberSampath Lokuge1-Oct-14 8:25 
QuestionList of Listboxes :) PinmemberBorrierulez19-Mar-14 3:28 
AnswerRe: List of Listboxes :) PinmemberSampath Lokuge19-Mar-14 4:51 
AnswerRe: List of Listboxes :) PinmemberBorrierulez19-Mar-14 8:36 
GeneralRe: List of Listboxes :) PinmemberSampath Lokuge19-Mar-14 20:42 
GeneralRe: List of Listboxes :) PinmemberBorrierulez24-Mar-14 4:47 
GeneralRe: List of Listboxes :) PinmemberSampath Lokuge24-Mar-14 12:17 
GeneralRe: List of Listboxes :) PinmemberBorrierulez9-Apr-14 6:35 
GeneralRe: List of Listboxes :) PinmemberSampath Lokuge10-Apr-14 1:51 
QuestionLinq statement with .ToString() PinmemberCorn Fed3-Dec-13 6:11 
AnswerRe: Linq statement with .ToString() PinmemberSampath Lokuge3-Dec-13 20:47 
QuestionHow to implement select all function in it [modified] Pinmembermanish2kk18-Nov-13 8:31 
AnswerRe: How to implement select all function in it PinmemberSampath Lokuge19-Nov-13 2:26 
QuestionDropDownList to refresh data in checkbox list PinmemberWoody10016-Oct-13 14:12 
AnswerRe: DropDownList to refresh data in checkbox list PinmemberSampath Lokuge16-Oct-13 21:13 
GeneralRe: DropDownList to refresh data in checkbox list PinmemberWoody10017-Oct-13 10:24 
GeneralRe: DropDownList to refresh data in checkbox list PinmemberWoody10017-Oct-13 15:22 
GeneralMy vote of 5 Pinmembermanoj.jsm8-Jul-13 3:44 
GeneralRe: My vote of 5 PinprofessionalSampath Lokuge8-Jul-13 3:53 
GeneralMy vote of 5 PinmemberUnque7-Jul-13 22:03 
GeneralRe: My vote of 5 PinprofessionalSampath Lokuge7-Jul-13 22:06 
QuestionTwitterBootstrapMvc imlpementation PinmemberDmitry A. Efimenko7-Jul-13 11:19 
AnswerRe: TwitterBootstrapMvc imlpementation PinprofessionalSampath Lokuge7-Jul-13 11:33 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411019.1 | Last Updated 8 Jul 2013
Article Copyright 2013 by Sampath Lokuge
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid