In this article I will explain with an example, how to retain selection of CheckBox inside WebGrid on PostBack (Form Submit) in ASP.Net MVC Razor.
 
Database
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.
Retain WebGrid CheckBox selection on PostBack (Form Submit) in ASP.Net MVC
 
 
Controller
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());
    }
 
    [HttpPost]
    public ActionResult Index(string [] chkRow)
    {
        if (chkRow != null)
        {
            TempData["Message"] = string.Join(",", chkRow);
        }
        return RedirectToAction("Index");
    }
}
 
 
View
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>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
 
        .Grid
        {
            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;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @webGrid.GetHtml(
                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")))
        <br/>
        <input type="submit" value="Submit"/>
        <hr/>
        @TempData["Message"]
    }
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></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.
            chkHeader.click(function () {
                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 () {
                UpdateHeaderRowCheckBox(chkHeader);
            });
 
            //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.
            UpdateHeaderRowCheckBox(chkHeader);
        });
 
        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.
                chkHeader.removeAttr("checked");
            }
        }
    </script>
</body>
</html>
 
 
Screenshot
Retain WebGrid CheckBox selection on PostBack (Form Submit) in ASP.Net MVC
 
 
Downloads