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.

Database

We will use the table below in our tutorial:

SQL

USE [TutorialsPanel]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

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

Namespaces

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

C#

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

VB.NET

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

Model

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.

Controllers

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.

C#

 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;
                    connection.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            items.Add(new SelectListItem { Text = reader["LanguageName"].ToString(), Value = reader["ID"].ToString() });
                        }
                    }
                    connection.Close();
                }
            }

            return View(items);
        }
}
        [HttpPost]
        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);
        }

VB.NET

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
                connection.Open()
                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

                connection.Close()
            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
    Next

    Return View(items)
End Function
End Class

View

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.

Martkup

@model List<SelectListItem>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Select Programming Languages</title>
 
</head>
<body>
    @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++)
            {
                <tr>
                    <td>
                        @Html.CheckBoxFor(m => m[i].Selected)
                    </td>
                    <td>
                        @Html.DisplayFor(m => m[i].Text)
                        @Html.HiddenFor(m => m[i].Value)
                        @Html.HiddenFor(m => m[i].Text)
                    </td>
                </tr>
             
            }
            <tr><td><input type="submit" value="Submit" /></td></tr>
        </table>

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

Now run the application

checkbox alert

Related Articles:

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *