@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>