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

CheckBoxList ASP.NET MVC3

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
8 Sep 2012CPOL2 min read 28.4K   7   3
Custom CheckBoxList in ASP.NET MVC3

Introduction

ASP.NET MVC3 does not provide built in control for implementing CheckBoxList. While working in my project, I was assigned a User Story which required such an implementation. After searching a lot on the internet, I did not find the feasible solution. Hence, I tried this on my own and have banged my head a lot of times while implementing. Well, this is my first tip, hence excuse me for any mistakes and also help rectify them.

Background

This implementation is on ASP.NET MVC3, NHibernate, linq. It is best suited for fixed size CheckBoxList.

Using the Code

In the Model class, include the enum for which CheckBoxList is to be created. Enum value should be of the order 2^n as shown below:

C#
[Flags]//Indicates that an enumeration can be treated as a bit field; i.e., as a set of flags
public enum ReportTemplateFormat
{
PDF = 1,
Excel = 2,
Word = 4,
CSV = 8
} 

Include another enum which has values similar to below:

C#
public enum ReportFormat
{
PDF = 0,
Excel = 1,
Word = 2,
CSV = 3
}

Include bool list in the ViewModel.

C#
public List<bool> ReportFormats { get; set; } 

In the Model, include an int property. Same to be included in the database.

C#
public virtual int AvailableFormats { get; set; }

In the create viewmodel from the model:

  1. When creating viewmodel, pass AvailableFormats(int) from model and assign to List<bool> used for checking the checkbox:
    C#
    viewModel.ReportFormats = GetFormats(model.AvailableFormats);
  2. Method to return List<bool> from the AvailableFormats(int) value passed.
    C#
    public List<bool> GetFormats(int reportFormats)
    {
    var reportTemplateFormat = new List<bool>();
    var reportTemplateFormatValues = 
    (ReportTemplateFormat[])Enum.GetValues(typeof(ReportTemplateFormat));
    //For new template and for existing templates 
    //with null values, all formats should be selected. 
    if(reportFormats==0)
    {
    for (var i = 0; i < reportTemplateFormatValues.Count(); i++)
    {
    reportFormats += (int)reportTemplateFormatValues[i];
    }
    }
    for (var i = 0; i < reportTemplateFormatValues.Count(); i++)
    {
    reportTemplateFormat.Add(new bool());
    }
    foreach (var x in reportTemplateFormatValues)
    {
    //XORing and assigning true value to the bool List
    if ((int)x != 0 && (reportFormats & (int)x) == (int)x)
    {
    ReportFormat reportFormat;
    if (Enum.TryParse(x.ToString(), true, out reportFormat))
    {
    reportTemplateFormat[(int)reportFormat] = true;
    }
    else
    {
    throw new ArgumentException(string.Format("Invalid Format '{0}'!", x));
    }
    }
    }
    return reportTemplateFormat;
    }

In update model from viewmodel:

  1. Update the AvailableFormats property in the model by passing the List<bool> which contains the checked values from the checkbox list.
    C#
    model.AvailableFormats = GetAvailableFormats(viewModel.ReportFormats);
  2. Pass the List<bool> and return the evaluated AvailableFormats to be saved to model.
    C#
    //Evaluating selected values
    public int GetAvailableFormats(List<bool> reportTemplateFormats)
    {
    int reportTemplateFormat = 0;
    var reportTemplateValues = (ReportTemplateFormat[]) 
    	Enum.GetValues(typeof (ReportTemplateFormat));
    for (int i = 0; i < reportTemplateFormats.Count; i++)
    {
    if (reportTemplateFormats[i])
    reportTemplateFormat += Convert.ToInt32(reportTemplateValues[i]);
    }
    return reportTemplateFormat;
    }
  3. Implementation of the CheckBoxList in view.
    HTML
    <div class="float-editor-row"> 
    <div class="float-editor-label">@Html.Label("* Report Format")</div> 
    <div class="float-editor-field">
    @for (var i = 0; i < Model.ReportFormats.Count; i++)
    {
    //Using ReportFormats List<bool> to check the checkbox
    @Html.CheckBoxFor(x => x.ReportFormats[i], new { @checked = "checked" })
    @Html.LabelFor(x => x.ReportFormats[i], ((ReportFormat)i).ToString())<text>&nbsp;</text>
    }
    </div>
    </div>

Points of Interest

Well, this is my first article and I am sure there's lot of mistakes. It's very nice to share knowledge with everyone, that's the way even I have learned and thanks to all of them. I am open to criticism and please suggest to me the points to improve my writing skills.

History

This was implemented in my current project. Soon I would like to create a basic project based on the comments.

Thanks.

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionthx Pin
Pavel Vaclavek17-Nov-14 9:37
Pavel Vaclavek17-Nov-14 9:37 
Questionthank you Pin
antoxa.zimm2-Dec-12 21:05
antoxa.zimm2-Dec-12 21:05 
QuestionNice Article. Pin
RajkumarBathula8-Sep-12 23:33
RajkumarBathula8-Sep-12 23:33 

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.