In this article I will explain with an example, how to validate at-least one CheckBox is checked (selected) from a group of multiple CheckBoxes in ASP.Net MVC Razor.
There is no Data Annotation attribute to perform at-least one CheckBox checked (selected) validation in a group of multiple CheckBoxes, hence the validation will be performed using jQuery in ASP.Net MVC Razor.
The list of CheckBoxes will be populated from database using Model in ASP.Net MVC Razor.
Note: For beginners in using ADO.Net with ASP.Net MVC, please refer my article ASP.Net MVC: ADO.Net Tutorial with example.
 
 
Database
This article makes use of a table named Fruits whose schema is defined as follows.
Validate at-least one CheckBox checked (selected) in ASP.Net MVC Razor
 
The Fruits table has the following records.
Validate at-least one CheckBox checked (selected) in ASP.Net MVC Razor
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
 
 
Model
This article uses SelectListItem class as Model which is an in-built ASP.Net MVC class. It has all the properties needed for populating a CheckBoxList.
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the records from the Fruits table are fetched using DataReader and generic list of SelectListItem class is populated.
The FruitName is stored in the Text property while the FruitId is stored in the Value property.
 
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
Note: This example uses Model class object for capturing Form field values, for more details please refer my article ASP.Net MVC: Form Submit (Post) example.
 
When the Form is submitted, the posted values are captured through the SelectListItem class object.
Then a loop is executed over the generic list of SelectListItem class objects and the selected Fruit names are set into a ViewBag object which will be later displayed in View using JavaScript Alert Message Box.
Note: For more details on displaying message using JavaScript Alert MessageBox, please refer my article ASP.Net MVC: Display Message from Controller in View using JavaScript Alert MessageBox.
 
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        List<SelectListItem> items = new List<SelectListItem>();
        string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = " SELECT FruitName, FruitId FROM Fruits";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        items.Add(new SelectListItem
                        {
                            Text = sdr["FruitName"].ToString(),
                            Value = sdr["FruitId"].ToString()
                        });
                    }
                }
                con.Close();
            }
        }
 
        return View(items);
    }
 
    [HttpPost]
    public ActionResult Index(List<SelectListItem> items)
    {
        ViewBag.Message = "Selected Items:\\n";
        foreach (SelectListItem item in items)
        {
            if (item.Selected)
            {
                ViewBag.Message += string.Format("{0}\\n", item.Text);
            }
        }
        return View(items);
    }
}
 
 
View
Inside the View, in the very first line the SelectListItem class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
 
Population
Inside the Form, a loop is executed over the generic list of SelectListItem class objects and an HTML Table is generated consisting of a CheckBox and two HiddenFields.
Note: HiddenFields are used for storing the Text and Value of the CheckBox for sending it back during Form Submission. They are also useful for retaining the Text and Value of the CheckBox across Form submissions.
 
Validation
The Submit Button has been assigned a jQuery Click event handler. When the Submit Button is clicked, if the count of the selected (checked) CheckBoxes is 0 then the error message is displayed and the Form submission is cancelled.
 
Submission
When the Submit Button is clicked, first the validation for at-least one CheckBox is checked (selected) is performed and if the validation is successful, the Form gets submitted and the Model object is sent to the Controller.
Finally, the selected Fruit names are displayed using JavaScript Alert Message Box.
@model List<SelectListItem>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
 
        .error {
            color: red;
            display: none;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table id="tblFruits">
            @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>
            }
        </table>
        <span class="error">Please select at-least one Fruit.</span>
        <br/>
        <br/>
        <input id="btnSubmit" type="submit" value="Submit"/>
    }
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnSubmit").click(function () {
                var checked_checkboxes = $("#tblFruits input[type=checkbox]:checked");
                if (checked_checkboxes.length == 0) {
                    $(".error").show();
                    return false;
                }
                return true;
            });
        });
    </script>
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
Validate at-least one CheckBox checked (selected) in ASP.Net MVC Razor
 
 
Downloads