Click here to Skip to main content
15,891,607 members
Articles / Web Development / HTML
Tip/Trick

ASP.NET MVC CheckBoxList Basic Implementation

Rate me:
Please Sign up or sign in to vote.
4.90/5 (10 votes)
15 Jun 2014CPOL2 min read 130.6K   9   11   4
This post is about how to demonstrate CheckBoxList in ASP.NET MVC 4

Introduction

In this post, I will explain two methods to implement CheckBoxList in ASP.NET MVC. I work in MVC 4 with .NET Framework 4.5.1 and Visual Studio 2013.

This post comes after I surfed a little bit of How to implement CheckBoxList in my new project.

Using the Code

Here, we will create ASP.NET MVC project to start with.

First: Write the Model

In the Models Folder, add the following classes:

C++
//
public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public ICollection<Group> Groups { get; set; }
    }
    public class Group
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<User> Users { get; set; }
    }
//

Our model will represent the user - group Relationship, it is clear it is many-to-many Relation, so we will manage user groups via checkListBox.

Note: This is not a complete example for managing Groups of users. It is just for clearing CheckBoxList.

Second: Write the ViewModel

Make a new folder in the solution. Name it ViewModel and add the class.

C++
//
public class UserViewModel
    {
        public User User { get; set; }
        public List<Group> AllGroups { get; set; }
        public List<Group> UserGroups { get; set; }
        public int[] SelectedGroups { get; set; }
    }
//

Third: Change Controller

Add the following method to HomeController.cs:

private UserViewModel InitilizeData()
        {
            UserViewModel userVM = new UserViewModel();
            userVM.User = new Models.User
            {
                ID = 1,
                Name = "Ahmed Omer",
                Password = "123123",
                Email = "a@b.c"

            };
            userVM.User.ID = 1;
            userVM.User.Name = "Ahmed Omer";
            userVM.User.Password = "123123";
            userVM.User.Email = "a@b.c";
            userVM.AllGroups = new List<Group>() {
                new Group {ID=1,Name="Group 1" },
                new Group {ID=2,Name="Group 2" },
                new Group {ID=3,Name="Group 3" },
                new Group {ID=4,Name="Group 4" },
                new Group {ID=5,Name="Group 5" }
            };

            userVM.UserGroups = new List<Group>()
            {
                userVM.AllGroups[4],
                userVM.AllGroups[1],
                userVM.AllGroups[2],
            };
            userVM.SelectedGroups = userVM.UserGroups.Select(x => x.ID).ToArray();
            return userVM;
        }

Index action should look like this:

C++
//
public ActionResult Index()
        {
            return View(InitilizeData());
        }
        [HttpPost]
        public ActionResult Index(UserViewModel model)
        {
            UserViewModel user = InitilizeData();
            user.SelectedGroups = model.SelectedGroups;
            //add code to manipulate user groups
            //foreach (var item in user.SelectedGroups)
            //{
            //    
            //}
            return View(user);
        }
//

Forth: Direct to View

In the index view, replace all code with the following:

HTML
@model CheckBoxList.ViewModels.UserViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>UserViewModel</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.User.ID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User.ID)
            @Html.ValidationMessageFor(model => model.User.ID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.User.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User.Name)
            @Html.ValidationMessageFor(model => model.User.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.User.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User.Password)
            @Html.ValidationMessageFor(model => model.User.Password)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.User.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User.Email)
            @Html.ValidationMessageFor(model => model.User.Email)
        </div>
        <ul>
            @foreach (var g in Model.AllGroups)
            {
                <li>
                    <input type="checkbox" 
                    name="SelectedGroups" value="@g.ID" id="@g.ID"
                           @{if (Model.SelectedGroups.Contains(g.ID)) 
                           { <text> checked='checked' </text>  } } />
                    <label for="@g.ID">@g.Name</label>
                </li>
            }
        </ul>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

The main code we are interested in is:

HTML
<ul>
            @foreach (var g in Model.AllGroups)
            {
                <li>
                    <input type="checkbox" 
                    name="SelectedGroups" 
                    value="@g.ID" id="@g.ID"
                           @{if (Model.SelectedGroups.Contains(g.ID)) 
                           { <text> checked='checked' </text>  } } />
                    <label for="@g.ID">@g.Name</label>
                </li>
            }
        </ul>

The ouput should look like this:

Image 1

Now you can post the form and make a break point to see the selected value is stored in model.SelectedGroups field.

This is the first method to implement CheckListBox.


In the scond method, we will use MvcCheckBoxList from NuGetPackage.

Steps are the same until 3. The difference is only in step 4 and also we have to install the package as the following:

Go to TOOlS > Library Package Manager > Package Manager Console and write this command:

install-package MvcCheckBoxList

After Package is installed, you should see something like this:

Image 2

Then, add the following code to your view:

HTML
<div class="editor-field">
            @Html.CheckBoxListFor(model=>model.SelectedGroups,
                                  model=>model.AllGroups,
                                  x=>x.ID,
                                  x=>x.Name,
                                  model=>model.UserGroups)
        </div>

The result is as follows:

Image 3

Of course, in the second method, you can have more options like set List Vertically or Horizontally.

Points of Interest

For more information about the second method, you can read this thread by Sampath Lokuge.

License

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


Written By
Software Developer ClickAppsCo
Yemen Yemen
I am Software developer and .Net Team Leader at ClickApps, I Hold a Bachelor degree in computer Engineering from Hadhramout University.
I am specialized in microsoft technologies like .Net, ASP, WPF, and many more

Comments and Discussions

 
QuestionNice one Pin
Member 1338498229-Aug-17 21:06
Member 1338498229-Aug-17 21:06 
QuestionClient Validation? Pin
robertfah23-Sep-14 9:00
robertfah23-Sep-14 9:00 
QuestionLooking for guidance Pin
Tridip Bhattacharjee15-Jun-14 20:53
professionalTridip Bhattacharjee15-Jun-14 20:53 
AnswerRe: Looking for guidance Pin
Ahmed Bakodah15-Jun-14 21:58
Ahmed Bakodah15-Jun-14 21:58 

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.