Introduction

I would like to share how to bind the checkbox list in MVC. I will use a Model (a class file) to define various attributes for checkboxes.

For a basic understanding of MVC kindly use the following link:

ASP.NET MVC Overview

The following is the procedure.

1. Creating Model
Creating Model
We created a "SubjectModel" class under the Models folder and defined the following two properties:

  1. Subject: to display text
  2. Selected: to display check/uncheck

2. Creating the controller
Creating Controller

  1. public ActionResult DisplayCheckboxes()
  2. {
  3. List<SubjectModel> listsubject = new List<SubjectModel>();
  4. listsubject.Add(new SubjectModel("Physics",true));
  5. listsubject.Add(new SubjectModel("Chemistry",true));
  6. listsubject.Add(new SubjectModel("History",false));
  7. listsubject.Add(new SubjectModel("Maths",false));
  8. listsubject.Add(new SubjectModel("Boilogy",false));
  9. listsubject.Add(new SubjectModel("Hindi",true));
  10. ViewData["Checkboxlist"]=listsubject;
  11. return View();
  12. }

3. Creating View

Right-click on "Action" and click on "Create view". The following screen will be displayed.
Code at View

4. Code at view
Code at View

Here we have a view and we are trying to bind a Checkbox using Model properties.

5. Output

Application Output

6. Binding checkboxes through strongly typed view

Binding CheckBox

The following would be the updated code for the Action:

  1. public ActionResult DisplayCheckboxes ()
  2. {
  3. List<SubjectModel> listsubject = new List<SubjectModel>();
  4. listsubject.Add(new SubjectModel("Physics", true));
  5. listsubject.Add(new SubjectModel("Chemistry", true));
  6. listsubject.Add(new SubjectModel("History", false));
  7. listsubject.Add(new SubjectModel("Maths", false));
  8. listsubject.Add(new SubjectModel("Boilogy", false));
  9. listsubject.Add(new SubjectModel("Hindi", true));
  10. return View(listsubject);
  11. }

7. Code at view

For a strongly typed view we have the following code.

View
The preceding line inherits "SubjectModel", which implies that the view is coupled with the Model.

Using a foreach loop as per the following, we can display a list of checkboxes using the DOM.

foreach loop to display list of checkbox

8. Output

We will get the same output as from point 5.

Conclusion

In this article, we have learned how to bind a checkbox list using MVC2. We have learned two ways to bind checkboxes; using a strongly typed view and without using a strongly typed view.

References

I had posted another article for binding a Dropdown list using MVC2:

Ways to Bind Dropdown List in ASP.Net MVC