Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET MVC CheckBoxList Basic Implementation

0.00/5 (No votes)
15 Jun 2014 5  
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:

//
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.

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

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

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

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

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:

Then, add the following code to your view:

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

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here