Pass multiple CheckBox values from View to Controller in ASP.Net MVC

Tutorials PanelPosted by

Check-boxes are quite common and find their place in almost any form that need to be submitted in websites. They provide easier way to capture user data without a requirement of typing things. We might be wondering ways to forward the check-box data to controller from our view using ASP .Net MVC Razor framework. They might be from a view group or a form. The task is a bit challenging as we require preserving all the checked, unchecked states in the list of checkboxes. Not only that they need to be rendered back correctly as they were preserved.

In this article we will help you out by easing the task. Usually these values are populated from the database (here we use an SQL database) to the view. Once user has selected values and tries to submit the form (may be using a submit button) all these values are sent to ASP .Net MVC Razor controller.

Let’s get started.


We will use the table below in our tutorial:


USE [TutorialsPanel]



CREATE TABLE [dbo].[ProgrammingLanguage] (
    [ID]           INT           NOT NULL,
    [LanguageName] NVARCHAR (50) NULL


For achieving the task you will require importing namespaces configuration, sqlClient, and collections.


using System.Configuration
using System.Data.SqlClient
using System.Collections.Generic


Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Collections.Generic


ASP .Net has a built in class called SelectListItem which has all the attributes along-with methods required for rendering and retrieving values from checkboxes. This class is used as a model.


In the controllers we require using two action-methods for GET and POST operations. In the GET operation we will be pulling out values from SQL database with the help of DataReader and pass it out to the SelectListItem class to render it on to the view. Post operation is used to send the checkbox data files filed by user back to the controller on a button click event. SelectListItem class is used for getting the values of checkboxes and populated to a viewBag object by looping over the SelectListItem.


 public class HomeController : Controller

        public ActionResult Index()
            List<SelectListItem> items = new List<SelectListItem>();
            string strConn = "Data Source=TutorialsPanel-PC\\SQLEXPRESS;Initial Catalog=TutorialsPanel;Integrated Security=True;Pooling=False";
            using (SqlConnection connection = new SqlConnection(strConn))
                string query = " SELECT ID, LanguageName FROM ProgrammingLanguage Order by LanguageName ASC";
                using (SqlCommand cmd = new SqlCommand(query))
                    cmd.Connection = connection;
                    using (SqlDataReader reader = cmd.ExecuteReader())
                        while (reader.Read())
                            items.Add(new SelectListItem { Text = reader["LanguageName"].ToString(), Value = reader["ID"].ToString() });

            return View(items);
        public ActionResult Index(List items)
            ViewBag.Message = "\\n";
            foreach (SelectListItem item in items)
                if (item.Selected)
                    ViewBag.Message += string.Format("{0}\\n", item.Text);
            return View(items);


Public Class HomeController
    Inherits Controller

    Public Function Index() As ActionResult
        Dim items As List(Of SelectListItem) = New List(Of SelectListItem)()
        Dim strConn As String = "Data Source=TutorialsPanel-PC\SQLEXPRESS;Initial Catalog=TutorialsPanel;Integrated Security=True;Pooling=False"
        Using connection As SqlConnection = New SqlConnection(strConn)
            Dim query As String = " SELECT ID, LanguageName FROM ProgrammingLanguage Order by LanguageName ASC"
            Using cmd As SqlCommand = New SqlCommand(query)
                cmd.Connection = connection
                Using reader As SqlDataReader = cmd.ExecuteReader()
                    While reader.Read()
                        items.Add(New SelectListItem With {.Text = reader("LanguageName").ToString(), .Value = reader("ID").ToString()})
                    End While
                End Using

            End Using
        End Using

        Return View(items)
    End Function

Public Function Index(ByVal items As List(Of SelectListItem)) As ActionResult
    ViewBag.Message = "\n"
    For Each item As SelectListItem In items
        If item.Selected Then
            ViewBag.Message += String.Format("{0}\n", item.Text)
        End If

    Return View(items)
End Function
End Class


View is usually created using the HTML.BeginForm function, where we use values from class SelectListItem which is used as a Model. The HTML.BeginForm has a few parameters like the ActionName, ControlerName and the FormMethod description action’s name, the controller where it is used and the type of action whether GET or POST is used. Now in order to display all the list items in the check-box a loop is required, populating required name and values from the SelectListItem. On Submitting the form these values from the SelectListItem is iterated over and the required values extracted and sent using the POST method to the database. Hence you have your task achieved, populate value from DB to the view and save the altered value back to the database.


@model List<SelectListItem>

    Layout = null;

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Select Programming Languages</title>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        <table align="center">
            <tr><td>select from list below</td></tr>
            @for (int i = 0; i < Model.Count(); i++)
                        @Html.CheckBoxFor(m => m[i].Selected)
                        @Html.DisplayFor(m => m[i].Text)
                        @Html.HiddenFor(m => m[i].Value)
                        @Html.HiddenFor(m => m[i].Text)
            <tr><td><input type="submit" value="Submit" /></td></tr>

        <br />
    @if (ViewBag.Message != null)
        <script type="text/javascript">
            window.onload = function () {
                alert("You have selected @ViewBag.Message");

Now run the application

checkbox alert

Related Articles:

One comment

Leave a Reply