In this article I will explain with an example, how add CheckBox to WebGrid Header Row in ASP.Net MVC Razor.
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Creating an Entity Data Model
The very first step is to create an ASP.Net MVC Application and connect it to the Northwind Database using Entity Framework. For more details please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example.
Following is the Entity Data Model of the Customers Table of the Northwind Database which will be used later in this project.
Add CheckBox to WebGrid Header in ASP.Net MVC
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the records from the database are fetched using Entity Framework and are returned to the View.
Action method for handling POST operation
This Action method gets called when the Submit button is clicked. It accepts an Array of String which is nothing but the values of the checked (selected) CheckBoxes in WebGrid.
Note: The parameter name chkRow is same as the name of the CheckBoxes in WebGrid and hence values of all the CheckBoxes which are checked are submitted and are available in the chkRow parameter.
The values present in the Array of String are joined using a Comma separator and are assigned to the TempData object.
Finally the Action is redirected.
public class HomeController : Controller
    // GET: Home
    public ActionResult Index()
        NorthwindEntities entities = new NorthwindEntities();
        return View(entities.Customers.Take(10).ToList());
    public ActionResult Index(string [] chkRow)
        if (chkRow != null)
            TempData["Message"] = string.Join(",", chkRow);
        return RedirectToAction("Index");
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that the Model will be available as a Collection.
The WebGrid is initialized with the Model i.e. IEnumerable collection of Customer Entity class objects as source.
Note: For more information on usage of WebGrid, please refer WebGrid Step By Step Tutorial with example in ASP.Net MVC.
Adding CheckBox to WebGrid Row
The first column in WebGrid is formatted to display a CheckBox and the CustomerID field value is assigned to the value attribute of the CheckBox.
Adding CheckBox to WebGrid Header Row
There is no direct way to add a CheckBox to the Header Row of WebGrid and hence, using jQuery a dynamic CheckBox is created and it is appended to the first cell of the Header row of the WebGrid.
Check (Select) Row CheckBoxes when the Header Row CheckBox is checked (selected)
The Header Row CheckBox is assigned a jQuery Click event handler. When the Header Row CheckBox is checked (selected), all the row CheckBoxes are checked (selected) using jQuery.
And in similar way, when the Header Row CheckBox is unchecked (deselected), all the row CheckBoxes are unchecked (deselected) using jQuery.
Check (Select) Header Row CheckBox when the all the Row CheckBoxes are checked (selected)
Each Row CheckBox is assigned a jQuery Click event handler. When any Row CheckBox is checked (selected), a check is perform to find whether all Row CheckBoxes are checked. If the answer is Yes, then the Header Row CheckBox is checked (selected) else the Header Row CheckBox is unchecked (deselected).
Retain CheckBox selection after Form Submit (PostBack)
The TempData object has all the values of CheckBoxes which were checked before the Form was submitted. First the value is extracted from TempData object and then it is split into an Array.
Finally a loop is executed over the Array items and all the Row CheckBoxes whose values are present in the Array are checked (selected).
@model IEnumerable<Customer>
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canPage: false, canSort: false);
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width"/>
    <style type="text/css">
            font-family: Arial;
            font-size: 10pt;
            border: 1px solid #ccc;
            border-collapse: collapse;
        .Grid th
            background-color: #F7F7F7;
            font-weight: bold;
        .Grid th, .Grid td
            padding: 5px;
            border: 1px solid #ccc;
        .Grid, .Grid table td
            border: 0px solid #ccc;
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
                htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
                columns: webGrid.Columns(
                         webGrid.Column(null, null, format: @<text><input type="checkbox" name="chkRow" value="@item.CustomerID"/></text>),
                         webGrid.Column("CustomerID", "Customer Id"),
                         webGrid.Column("ContactName", "Customer Name"),
                         webGrid.Column("City", "City"),
                         webGrid.Column("Country", "Country")))
        <input type="submit" value="Submit"/>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        $(function () {
            //Create the CheckBox element.
            var chkHeader = $("<input type = checkbox id = 'chkHeader' />");
            //Append it to the First cell of Header Row.
            $("#WebGrid th:first-child").append(chkHeader);
            //Assign Click event handler to the Header Row CheckBox.
   () {
                if ($(this).is(":checked")) {
                    //If the Header Row CheckBox is checked, check all Row CheckBoxes.
                    $("#WebGrid td input[type=checkBox]").attr("checked", "checked");
                } else {
                    //If the Header Row CheckBox is NOT checked, uncheck all Row CheckBoxes.
                    $("#WebGrid td input[type=checkBox]").removeAttr("checked");
            //Assign Click event handler to each Row CheckBox.
            $("#WebGrid input[name=chkRow]").click(function () {
            //Retain selection of Row CheckBoxes.
            var selected = "@TempData["Message"]".split(',');
            for (var i in selected) {
                $("#WebGrid input[value='" + selected[i] + "']").attr("checked", "checked");
            //Retain selection of Header Row CheckBox.
        function UpdateHeaderRowCheckBox(chkHeader) {
            if ($("#WebGrid td input[type=checkBox]:checked").length == $("#WebGrid td input[type=checkBox]").length) {
                //If all the Row CheckBoxes are checked, check the Header Row CheckBox.
                chkHeader.attr("checked", "checked");
            } else {
                //Even if one of the Row CheckBoxes is NOT checked, uncheck the Header Row CheckBox.
Add CheckBox to WebGrid Header in ASP.Net MVC