Click here to Skip to main content
15,891,529 members
Articles / Web Development / HTML

CheckBoxList(For) - A missing MVC extension (no longer supported)

Rate me:
Please Sign up or sign in to vote.
4.82/5 (44 votes)
4 Feb 2014CPOL6 min read 771.6K   15K   128   238
Extends MVC HtmlHelper class so you can create POSTable checkbox list.
This extension is no longer supported, meaning no new versions are being developed or planned to be released, if you still like to use it or modify it, source code is available on GitHub.

Check the official website for the live examples and documentation:

MvcCheckBoxList

Latest Version (for .NET 4.0 or 4.5 and MVC4)

Install via NuGet Package Manager Console:

Install-Package MvcCheckBoxList   

Download sample MVC project with extension's stable source code 

Contents

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. It is done by simply typing Html.<smth> on the MVC view page.

Its all been good and easily customizable, until developers been eventually reaching one blank spot... That spot was a creation of a checkbox lists. There was none, and there is no any control to handle that functionality as of now.

To create a checkbox list a developer would have to use a combination of FOR or FOREACH cycle and some html <input> along with it.

While not being a hard thing to do, it could possibly become pretty time consuming. Especially when project was getting bigger and fatter with a whole bunch of repetitive code lying around. And think about adding some advanced functionality and layout. For example, when we want to disable some checkboxes, while at the same time being able to POST it back to your controller, and on top of that, putting it into the <table>, it would become quite bigger than before.

But what if we would want to put it into several columns? It would require even more customization. And would get even bigger. This little extension intends to simplify this task while making it more inline with general MVC workflow.

This plugin is just an extension of MVC class 'HtmlHelper', which is used for all Html helpers on MVC views. Since there is no supported CheckBoxList extension built into MVC, this plugin adds it.  

Using the code 

All examples below are shown using MVC + Razor view engine. Examples will demonstrate recommended real-world scenario of using this extension.

Given we have...

Base class City:

C#
public class City {
  public int Id { get; set; }           // Integer value of a checkbox
  public string Name { get; set; }      // String name of a checkbox
  public object Tags { get; set; }      // Object of html tags to be applied to checkbox, e.g.: 'new { tagName = "tagValue" }'
  public bool IsSelected { get; set; }  // Boolean value to select a checkbox on the list
}   

And we use CitiesViewModel view model on our view:

C#
public class CitiesViewModel {
  public IList<City> AvailableCities { get; set; }
  public IList<City> SelectedCities { get; set; }
  public PostedCities PostedCities { get; set; }
}

// Helper class to make posting back selected values easier
public class PostedCities {
  public string[] CityIDs { get; set; }
} 

And our controller accepts class PostedCities:

C#
public ActionResult Examples(PostedCities postedCities) {
  return View(/* Create View Model */);
}           

Source: documentation > Given we have...

Base Overloads

Now we can create a control on the view, first - keep in mind base checkbox list call structure:

C#
@Html.CheckBoxList("LIST_NAME", 
                   model => model.LIST_DATA, 
                   entity => entity.VALUE, 
                   entity => entity.NAME, 
                   model => model.SELECTED_VALUES) // or entity => entity.IS_CHECKED

Or with strongly-typed name:

C#
@Html.CheckBoxListFor(model => model.LIST_NAME, 
                      model => model.LIST_DATA, 
                      entity => entity.VALUE, 
                      entity => entity.NAME, 
                      model => model.SELECTED_VALUES) // or entity => entity.IS_CHECKED 

So in our example it'll look like this:

C#
@Html.CheckBoxListFor(model => model.PostedCities.CityIDs, 
                      model => model.AvailableCities, 
                      entity => entity.Id, 
                      entity => entity.Name, 
                      model => model.SelectedCities) 

Or if using boolean selector: 

C#
@Html.CheckBoxListFor(model => model.PostedCities.CityIDs, 
                      model => model.AvailableCities, 
                      entity => entity.Id, 
                      entity => entity.Name, 
                      entity => entity.IsSelected)  

where entity.IsSelected is a boolean value from database, 

And another way to use boolean selector: 

C#
@Html.CheckBoxListFor(model => model.PostedCities.CityIDs, 
                      model => model.AvailableCities, 
                      entity => entity.Id, 
                      entity => entity.Name, 
                      entity => selectedIds.Contains(x.Id)) 

where selectedIds.Contains(x.Id) returns bool if item Id matches the list.  

Source: documentation > Base Overloads.

Basic Settings:

Since five base properties (see previous section) don't change, only extra ones will be shown, so placeholder ... means usage of five base properties. You might need to add this reference to your view first (namespace for Position enum and others):

C#
@using MvcCheckBoxList.Model 

1. Set position (direction) of the list:

C#
@Html.CheckBoxListFor( ... , Position.Horizontal) 

Position Can be Position.Horizontal, Position.Vertical, Position.Horizontal_RightToLeft, or Position.Vertical_RightToLeft where last two are to reverse checkbox and label for right-to-left languages 2. Set html attributes for both checkbox and label:

C#
@Html.CheckBoxListFor( ... , x => new { @class="class_name" }) // Tags will be applied to all checkbox/label combos  

Or get Tags object from database:

C#
@Html.CheckBoxListFor( ... , x => x.Tags) // x.Tags will be applied only to particular checkbox/label combo 

3. Set html attributes and position:

C#
@Html.CheckBoxListFor( ... , Position.Horizontal, x => new { @class="class_name" }) 

4. Set html attributes for all, disabled values, position, and individual html attributes (all attributes will be merged together):

C#
@Html.CheckBoxListFor( ... , x => new { @class="class_name" }, new[] {"3", "5", "7"}, Position.Horizontal, x => x.Tags) 

Source: documentation > Basic Settings.

Advanced Settings:

You might need to add this reference to your view first (namespace for HtmlListInfo class and others): 

C#
@using MvcCheckBoxList.Model 

1. Set custom layout using HtmlListInfo class: 

C#
var htmlListInfo = new HtmlListInfo(HtmlTag.table, 2, new { @class="class_name" }, TextLayout.Default, TemplateIsUsed.Yes);

@Html.CheckBoxListFor( ... , htmlListInfo)  

There, in HtmlListInfo class, HtmlTag can be HtmlTag.table or HtmlTag.vertical_columns; 2 is a number of columns; TextLayout can be TextLayout.Default or TextLayout.RightToLeft (for right to left languages) 

2. Set layout with HtmlListInfo class and set html attributes: 

C#
@Html.CheckBoxListFor( ... , htmlListInfo, x => new { tagName = "tagValue" })  // Tags will be applied to all checkbox/label combos 

Or get Tags object from database: 

@Html.CheckBoxListFor( ... , htmlListInfo, x => x.Tags })  // x.Tags will be applied only to particular checkbox/label combo  

3. Set html attributes for all, set layout with HtmlListInfo, set disabled values, and individual html attributes (all attributes will be merged together): 

C#
@Html.CheckBoxListFor( ... , new { @class="class_name" }, htmlListInfo, new[] {"3", "5", "7"}, x => x.Tags)  

There, x.Tags is a value of type object and should be equal to something similar to this new { tag1 = "value1", tag2="value2" } and represent one or more custom html attributes, and will be applied to both checkbox and label. 

Also note that x.Tags is an optional parameter for each available overload. Just add it as a last parameter to @Html.CheckBoxListFor( ... , x => x.Tags) checkbox list call.  

Source: documentation > Advanced Settings

Live Examples 

Official website (from source code) has a dedicated live examples section to demonstrate how this extension will work in various real-world scenarios.  

Please see this extension in action here:  Examples

History 

  • v.1.4.4.4
    • Adds support for both .NET 4.0 and 4.5
  • v.1.4.3.0
    • Added support for right-to-left languages (by flipping the order of checkbox and label)
    • Removed model-independent functionality
  • v.1.4.2.3
    • Fixed a bug where it requires MVC4 dependency (System.Web.WebPages 2.0.0.0), and doesn't work in MVC3 projects...
  • v.1.4.2.2
    • NuGet package added!
    • Additional parameter for both 'CheckBoxList' and 'CheckBoxListFor' - 'htmlAttributesExpr' allows to pass custom html tags from database to be applied to each individual checkbox (see good exaple of this in sample MVC3 project)
    • Improved name generation
    • Numerous other small fixes...
  • v.1.3c
    • Some minor bug fixes done
    • Created a sample MVC3 .NET 4.0 site which comes along with this control, so you can test it first hand!
  • v.1.3b
    • Added function annotations, some code cleanup
  • v.1.3a
    • Instead of plain checkbox name it now creates a label linked to checkbox, so you can also click on the label to select that checkbox! Many thanks to william0565 for idea !
  • v.1.3
    • 'CheckBoxListFor' now generates full name from a lambda expression: e.g.: @Html.CheckBoxListFor(model => model.SomeClass.SubClass .... ) will create a list of checkboxes with 'name="SomeClass.SubClass"', where older version would create only 'name="SubClass"'
  • v.1.2
    • You can now create strongly typed checkbox list from your view model!
    • Added new method 'CheckBoxListFor' to be used with strongly typed approach
  • v.1.1
    • Added new option 'HtmlTag.vertical_columns', which allows checkboxes to be arranged inside 4 vertically sorted floating sections
    • Overload functions cleanup
    • Overall code cleanup
  • v.1.0
    • Initial release!

Contributors

License

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


Written By
Web Developer
United States United States
Coding is awesome!

Comments and Discussions

 
GeneralRe: Development version 1.4.4.0 published on Github Pin
Dmitry A. Efimenko28-Aug-12 9:48
Dmitry A. Efimenko28-Aug-12 9:48 
GeneralRe: Development version 1.4.4.0 published on Github Pin
Mikhail-T29-Aug-12 4:56
Mikhail-T29-Aug-12 4:56 
GeneralRe: Development version 1.4.4.0 published on Github Pin
Dmitry A. Efimenko29-Aug-12 5:13
Dmitry A. Efimenko29-Aug-12 5:13 
NewsBUGS & ISSUES: Please report them on the Github (link below) Pin
Mikhail-T14-Aug-12 7:03
Mikhail-T14-Aug-12 7:03 
QuestionPossible updates Pin
Dmitry A. Efimenko6-Aug-12 11:20
Dmitry A. Efimenko6-Aug-12 11:20 
AnswerRe: Possible updates Pin
Mikhail-T6-Aug-12 12:25
Mikhail-T6-Aug-12 12:25 
GeneralRe: Possible updates Pin
Dmitry A. Efimenko6-Aug-12 12:45
Dmitry A. Efimenko6-Aug-12 12:45 
GeneralRe: Possible updates Pin
Dmitry A. Efimenko6-Aug-12 21:09
Dmitry A. Efimenko6-Aug-12 21:09 
So I have made changes that take care of Proposition 1 and it looks like it works great.
Also, I tried to apply htmlAttributes to each element using the expression that I mentioned in Proposition 2 and it throws an error: bla blah... cannot be inferred from the usage. Try specifying the type arguments explicitly. Possibly your resharper was getting around this issue as well.
So I updated it according to my suggestion and it works as expected.
Now, should I upload project with these changes somewhere for you to look?

I've done some further investigation of the code and functionality and I think I found some more areas where we could improve this extension:

1.
I think it would be a good idea to put the whole output into a <div> with a default class applied. Of course you could put the whole thing into a div manually, but we are making it easier for the user, right ? Smile | :)
I think it should be taken even a step further: each combination of input and label should be put into it's own div with a default class applied.
Sample output would be:
HTML
<div class="check-box-list">
    <div class="check-box-list-block">
        <input id="..." name="..." value="..." /><label for="...">...</label>
    </div>
    <div class="check-box-list-block">
        <input id="..." name="..." value="..." /><label for="...">...</label>
    </div>
</div>

The reason for the main wrapping div is to allow a bit easier hook to the whole list of checkboxes.
The reason for inner wrapper divs is to have a hook to format paddings or margins or whatever of each block.


2.
consider overload #7:
public static MvcHtmlString CheckBoxListFor<TModel, TProperty, TItem, TValue, TKey>
    (this HtmlHelper<TModel> htmlHelper,
     Expression<Func<TModel, TProperty>> listNameExpr,
     Expression<Func<TModel, IEnumerable<TItem>>> sourceDataExpr,
     Expression<Func<TItem, TValue>> valueExpr,
     Expression<Func<TItem, TKey>> textToDisplayExpr,
     Expression<Func<TItem, bool>> isSelectedExpr,
     object htmlAttributes,
     Position position,
     Expression<Func<TItem, object>> htmlAttributesExpr)

It seems that currently object htmlAttributes is used to add the same attributes to each input and label. But this is pretty much the purpose of htmlAttributesExpr parameter. Currently if we use both of them, the htmlAttributesExpr will override htmlAttributes. If we had the whole thing inside a div, we could use htmlAttributes to specify class or id for that div and leave inputs to be handled by the expression.

3.
As I mentioned before, htmlAttributesExpr will apply same attributes to both input and label. Consider this example:
C#
@Html.CheckBoxListFor(x => x.CityIdsSelected,
                x => x.Cities,
                x => x.Id,
                x => x.Name,
                x => Model.CityIdsSelected.Contains(x.Id),
                x => new { @data_target = "target-city-id-" + x.Key.ToString() })

Lets say I will be hooking up some ajax that will look up target by that data-target attribute that I attach to the input. There surely no need to have the same attribute on the label. Seems like duplication to me.

4.
I have to look a bit closer into the use Position and HtmlListInfo, but they seem a bit repetitive to me. Perhaps there is a way to combine these into one. I'll see what can be done there after you tell me what you think about first three items.

Sorry for the lengthy answers...
AnswerRe: Possible updates Pin
Mikhail-T7-Aug-12 4:19
Mikhail-T7-Aug-12 4:19 
NewsRe: Possible updates Pin
Mikhail-T8-Aug-12 6:21
Mikhail-T8-Aug-12 6:21 
NewsRe: Possible updates Pin
Mikhail-T25-Aug-12 6:07
Mikhail-T25-Aug-12 6:07 
GeneralRe: Possible updates Pin
Dmitry A. Efimenko25-Aug-12 14:28
Dmitry A. Efimenko25-Aug-12 14:28 
GeneralRe: Possible updates Pin
Mikhail-T27-Aug-12 3:51
Mikhail-T27-Aug-12 3:51 
QuestionEnhancement to use Display Template Pin
emillium30-Jul-12 17:00
emillium30-Jul-12 17:00 
AnswerRe: Enhancement to use Display Template Pin
Mikhail-T31-Jul-12 3:58
Mikhail-T31-Jul-12 3:58 
GeneralRe: Enhancement to use Display Template Pin
emillium1-Aug-12 1:42
emillium1-Aug-12 1:42 
GeneralRe: Enhancement to use Display Template Pin
Mikhail-T1-Aug-12 3:26
Mikhail-T1-Aug-12 3:26 
GeneralRe: Enhancement to use Display Template Pin
emillium13-Aug-12 14:53
emillium13-Aug-12 14:53 
AnswerRe: Enhancement to use Display Template Pin
Mikhail-T14-Aug-12 6:55
Mikhail-T14-Aug-12 6:55 
NewsRe: Enhancement to use Display Template Pin
Mikhail-T25-Aug-12 6:05
Mikhail-T25-Aug-12 6:05 
QuestionHow to add a small hyperlinked image next to a specific checkbox item label? Pin
tracsorenson24-Jul-12 12:04
tracsorenson24-Jul-12 12:04 
AnswerRe: How to add a small hyperlinked image next to a specific checkbox item label? Pin
Mikhail-T25-Jul-12 4:34
Mikhail-T25-Jul-12 4:34 
GeneralRe: How to add a small hyperlinked image next to a specific checkbox item label? Pin
tracsorenson25-Jul-12 8:41
tracsorenson25-Jul-12 8:41 
GeneralRe: How to add a small hyperlinked image next to a specific checkbox item label? Pin
Mikhail-T25-Jul-12 10:20
Mikhail-T25-Jul-12 10:20 
QuestionHelper not showing up in intellisense Pin
mtosic18-Jul-12 5:00
mtosic18-Jul-12 5:00 

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.