Click here to Skip to main content
11,649,476 members (77,164 online)
Click here to Skip to main content

CheckBoxList(For) - A missing MVC extension

, 4 Feb 2014 CPOL 326K 12.9K 126
Rate this:
Please Sign up or sign in to vote.
Extends MVC HtmlHelper class so you can create POSTable checkbox list.

Check out official website with live examples and documentation:

mvccbl.com

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

Install via NuGet Package Manager Console:

Install-Package MvcCheckBoxList

Download binary (MvcCheckBoxList.dll)

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:

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 CitiesViewModelview model on our view:
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:
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:
@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:
@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:
@Html.CheckBoxListFor(model => model.PostedCities.CityIDs, 
                      model => model.AvailableCities, 
                      entity => entity.Id, 
                      entity => entity.Name, 
                      model => model.SelectedCities)

Or if using boolean selector: 

@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: 

@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):
@using MvcCheckBoxList.Model
1. Set position (direction) of the list:
@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:
@Html.CheckBoxListFor( ... , x => new { @class="class_name" }) // Tags will be applied to all checkbox/label combos
Or get Tags object from database:
@Html.CheckBoxListFor( ... , x => x.Tags) // x.Tags will be applied only to particular checkbox/label combo
3. Set html attributes and position:
@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):
@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): 

@using MvcCheckBoxList.Model 

1. Set custom layout using HtmlListInfoclass: 

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

@Html.CheckBoxListFor( ... , htmlListInfo)  

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

2. Set layout with HtmlListInfoclass and set html attributes: 

@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): 

@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:  mvccbl.com > 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)

Share

About the Author

Mikhail-T
Web Developer
United States United States
Coding is awesome!

You may also be interested in...

Comments and Discussions

 
QuestionHow to create a simple checkboxlist without model Pin
Member 115402016-May-15 20:57
memberMember 115402016-May-15 20:57 
QuestionHow to disable all checked box Pin
Member 104614707-Apr-15 18:06
professionalMember 104614707-Apr-15 18:06 
QuestionHow to use in Razor when in another ViewModel Pin
Member 1131794817-Dec-14 4:36
memberMember 1131794817-Dec-14 4:36 
Questionhtml markup Pin
Member 1098399331-Jul-14 7:45
memberMember 1098399331-Jul-14 7:45 
AnswerRe: html markup Pin
Tieson22-Jul-15 20:32
memberTieson22-Jul-15 20:32 
GeneralMy vote of 3 Pin
swapnil_jadhav16-Jul-14 0:56
professionalswapnil_jadhav16-Jul-14 0:56 
BugStrange override error Pin
Member 392317129-Jun-14 18:59
memberMember 392317129-Jun-14 18:59 
QuestionHide tickbox Pin
Member 439133126-May-14 21:21
memberMember 439133126-May-14 21:21 
AnswerRe: Hide tickbox Pin
Mikhail-T28-May-14 3:56
memberMikhail-T28-May-14 3:56 
General5 stars Pin
Mystcreater1-May-14 9:32
memberMystcreater1-May-14 9:32 
GeneralRe: 5 stars Pin
Mikhail-T4-May-14 4:45
memberMikhail-T4-May-14 4:45 
QuestionJquery post value is null Pin
Blunts1-May-14 4:17
memberBlunts1-May-14 4:17 
AnswerRe: Jquery post value is null [Fixed] Pin
Blunts1-May-14 9:30
memberBlunts1-May-14 9:30 
GeneralRe: Jquery post value is null [Fixed] Pin
Mikhail-T4-May-14 4:43
memberMikhail-T4-May-14 4:43 
QuestionHow can I modify template of whole checkbox list Pin
Member 106345828-Apr-14 21:40
memberMember 106345828-Apr-14 21:40 
AnswerRe: How can I modify template of whole checkbox list Pin
Mikhail-T9-Apr-14 6:12
memberMikhail-T9-Apr-14 6:12 
QuestionCheckBoxList reset after validation failure Pin
melodystar6-Mar-14 10:02
professionalmelodystar6-Mar-14 10:02 
QuestionRe: CheckBoxList reset after validation failure Pin
Ken McAndrew17-Dec-14 17:05
memberKen McAndrew17-Dec-14 17:05 
QuestionAny sample with validation on client? Pin
Bellinat4-Mar-14 3:23
memberBellinat4-Mar-14 3:23 
QuestionPost back returning Null in the controller. Pin
Member 1029462018-Feb-14 9:23
memberMember 1029462018-Feb-14 9:23 
AnswerRe: Post back returning Null in the controller. Pin
Mikhail-T19-Feb-14 4:12
memberMikhail-T19-Feb-14 4:12 
GeneralRe: Post back returning Null in the controller. Pin
Member 1029462021-Feb-14 4:07
memberMember 1029462021-Feb-14 4:07 
QuestionPosition.Vertical ... still available? Pin
Member 1047434218-Dec-13 3:14
memberMember 1047434218-Dec-13 3:14 
AnswerRe: Position.Vertical ... still available? Pin
Mikhail-T4-Feb-14 12:02
memberMikhail-T4-Feb-14 12:02 
QuestionException: View Model cannot be null! I FOUND THE SOLUTION!!! Pin
denko8314-Dec-13 9:47
memberdenko8314-Dec-13 9:47 
AnswerRe: Exception: View Model cannot be null! I FOUND THE SOLUTION!!! Pin
Mikhail-T4-Feb-14 11:57
memberMikhail-T4-Feb-14 11:57 
GeneralRe: Exception: View Model cannot be null! I FOUND THE SOLUTION!!! Pin
deo cabral7-Apr-15 19:18
professionaldeo cabral7-Apr-15 19:18 
Questionvalidation Pin
monkeymanblahblah12-Dec-13 8:24
membermonkeymanblahblah12-Dec-13 8:24 
Questionstring[] disabled bug Pin
Member 1043064727-Nov-13 12:43
memberMember 1043064727-Nov-13 12:43 
QuestionSelect all functionality Pin
manish2kk18-Nov-13 7:52
membermanish2kk18-Nov-13 7:52 
QuestionReference to MvcCheckBoxList is missing in views Pin
Member 103822355-Nov-13 11:20
memberMember 103822355-Nov-13 11:20 
QuestionCustomize "No Records..." message Pin
CiganoMorrison20-Oct-13 9:31
memberCiganoMorrison20-Oct-13 9:31 
AnswerRe: Customize "No Records..." message Pin
Mikhail Tsennykh22-Oct-13 6:19
memberMikhail Tsennykh22-Oct-13 6:19 
QuestionCSS div/section formatting Pin
Paul Schwotzer16-Oct-13 9:31
memberPaul Schwotzer16-Oct-13 9:31 
AnswerRe: CSS div/section formatting Pin
Mikhail Tsennykh16-Oct-13 11:35
memberMikhail Tsennykh16-Oct-13 11:35 
QuestionException: View Model cannot be null! Pin
MAjbO15-Oct-13 23:23
memberMAjbO15-Oct-13 23:23 
AnswerRe: Exception: View Model cannot be null! Pin
Mikhail Tsennykh16-Oct-13 11:23
memberMikhail Tsennykh16-Oct-13 11:23 
AnswerRe: Exception: View Model cannot be null! Pin
denko8314-Dec-13 9:49
memberdenko8314-Dec-13 9:49 
Questionmy project uses VS2010 .NET4.0,references your dll,while F5 start debug,then reports error Pin
Member 103270529-Oct-13 23:55
memberMember 103270529-Oct-13 23:55 
AnswerRe: my project uses VS2010 .NET4.0,references your dll,while F5 start debug,then reports error Pin
Mikhail Tsennykh16-Oct-13 11:18
memberMikhail Tsennykh16-Oct-13 11:18 
QuestionPosted object Pin
Member 103125625-Oct-13 19:17
memberMember 103125625-Oct-13 19:17 
AnswerRe: Posted object Pin
Member 103125625-Oct-13 22:43
memberMember 103125625-Oct-13 22:43 
AnswerRe: Posted object Pin
Mikhail Tsennykh16-Oct-13 11:14
memberMikhail Tsennykh16-Oct-13 11:14 
QuestionPosted data Pin
Member 103174865-Oct-13 8:03
memberMember 103174865-Oct-13 8:03 
AnswerRe: Posted data Pin
Mikhail Tsennykh16-Oct-13 11:10
memberMikhail Tsennykh16-Oct-13 11:10 
QuestionHow to configure to MVC (aspx) project without nuget install Pin
okdone24-Sep-13 23:30
memberokdone24-Sep-13 23:30 
AnswerRe: How to configure to MVC (aspx) project without nuget install Pin
Mikhail Tsennykh25-Sep-13 6:15
memberMikhail Tsennykh25-Sep-13 6:15 
QuestionConstant NoNullAllowedException ocurred Pin
denko8323-Sep-13 8:19
memberdenko8323-Sep-13 8:19 
AnswerRe: Constant NoNullAllowedException ocurred Pin
Mikhail Tsennykh23-Sep-13 11:41
memberMikhail Tsennykh23-Sep-13 11:41 
QuestionRe: Constant NoNullAllowedException ocurred Pin
denko8324-Sep-13 6:55
memberdenko8324-Sep-13 6:55 

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
Web04 | 2.8.150804.4 | Last Updated 4 Feb 2014
Article Copyright 2011 by Mikhail-T
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid