Ajax webgrid with paging and sorting in MVC

This articale will show you Ajax paging and sorting in webgrid. basic difference between normal webgrid and ajax grid is ajaxUpdateContainerId: “grid” just maintain grid id or grid container ID “gridContent” in this attribute.

Here is code

<div  id="gridContent" >
    var grid = new WebGrid(Model.students, canPage: true, rowsPerPage: 5, canSort: true, ajaxUpdateContainerId: "grid");
    @grid.GetHtml(htmlAttributes: new { id = "grid" },
        columns: grid.Columns(
             grid.Column("", format: @<text>@Html.CheckBox("chk") </text>),
             grid.Column("Name", format: @<text>@item.Name</text>),
             grid.Column("School Name", header: "SchoolName", format: @<text>@item.SchoolName</text>)

Now in the same grid if you want to add a row, like column sum at the bottom of grid. for that we have one more attribute ajaxUpdateCallback: “CalculateSum”   ajaxUpdateCallback will get executed when grid loads after ajax call, its similler to document.ready function  which will execute once document load .

Here is example

<style type="text/css" >
.datagrid{ background-color:White; }
.datagrid table { margin: 1em; border-collapse: collapse; }
td, th { padding: .3em; border: 1px #ccc solid; }
thead { background: #E8EEF4; }
.price{  }

<script type="text/javascript">

$(document).ready(function () {

function ShowTotal() {

function CalculateSum() {
var total = 0;
$('#gridContent .price').each(function () {
total = total + parseFloat($(this)[0].innerHTML.toLocaleString());
$('tbody').append('<tr><td><b>Total</b></td><td><b>' + total.toFixed(2) + '</b></td></tr>');


<div id="gridContent"  style=" padding:20px; " class="datagrid">
var grid = new WebGrid(Model, defaultSort: "Name", rowsPerPage: 10, ajaxUpdateContainerId: "gridContent", ajaxUpdateCallback: "ShowTotal");

@grid.GetHtml(tableStyle: "table",mode: WebGridPagerModes.All,
grid.Column("Name", format: @<text>@Html.ActionLink((string)item.Name, "Details", "Product", new { id = item.ID }, null)</text>),
grid.Column("Price", header: "Product Price", format: @<text> @item.Price.ToString("0.00")</text> ,style: "price" ))

<div>  </div>

This entry was posted in Ajax, ASP.NET MVC Web Grid, MVC and tagged , , . Bookmark the permalink.

One Response to Ajax webgrid with paging and sorting in MVC

  1. Rajesh says:

    Thanks a lot. This is what I was looking for. Keep up the good work. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s