ASP.NET MVC WebGrid – Performing true AJAX pagination and sorting

ASP.NET MVC WebGrid – Performing true AJAX pagination and sorting

 

FEBRUARY 27, 2012 14 COMMENTS

WebGrid is a very powerful HTML helper component introduced with ASP.NET MVC 3 and ASP.NET Web Pages. Despite all its cool features, it is troublesome to use it in real enterprise web applications since it does not have true AJAX support for sorting and pagination.

Its AJAX support is limited to retrieving the full page and then filtering out the contents of the container div tag using jQuery. This is even worse than UpdatePannel in ASP.NET WebForms (UpdatePannel only return the HTML that needs to be updated rather than the full HTML page). If the page has lots of other data (outside the grid) to display or if it has multiple grids, then the situation become worse. This support is sufficient for ASP.NET Web Page applications. However this is not what is expected from an ASP.NET MVC application.

However we can easily find a solution to this problem using jQuery. This can be achieved as follows.

The first step is to separate the grid implementation into a partial page that is loaded via a separate controller action. In my example, I assume that the grid is displayed using index action of the StudentController class. Then I break this index action into two actions (by introducing new “StudentGrid” action) as shown below.

public const int PageSize = 4;
public const string StudentGridAction = "StudentGrid";

public ActionResult Index()
{
     return View();
}

[ActionName(StudentGridAction)]
public ActionResult StudentGrid(string page, string sort, string sortdir)
{
     int pageNo = 0;
     if (!string.IsNullOrEmpty(page))
     {
          pageNo = int.Parse(page) - 1;
     }

     var result = GetStudents(sort, sortdir, pageNo);
     var model = new StudentGridModel();
     model.Students = result.Students;
     model.RowCount = result.Count;
     model.CurrentPage = pageNo;
     return PartialView(model);
}

Then I break the corresponding index.cshtml file into cshtml files as shown below,

Index.cshtml file:

@using MyApplicationNs.Controllers
@{
     ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="studentGrid">
     @Html.Action(StudentController.StudentGridAction)
</div>

StudentGrid.cshtml file:

@model MyApplicationNs.Models.Student.StudentGridModel
@using MyApplicationNs.Controllers
@{
     WebGrid studentGrid = new WebGrid(rowsPerPage: StudentController.PageSize);
     studentGrid.Bind(Model.Students, autoSortAndPage: false, rowCount: Model.RowCount);
     studentGrid.PageIndex = Model.CurrentPage;
}

@studentGrid.GetHtml(columns: new WebGridColumn[]{
    studentGrid.Column("StudentId", "Id"),
    studentGrid.Column("Name", "Name"),
    studentGrid.Column("Address","Address")})

After this refactoring, my grid works exactly as it worked before.

In order to ensure that only the grid content generated using new “StudentGrid” action is loaded when pagination and sorting links are clicked, I have added the following JavaScript block that uses jQuery at the bottom of index.csthml page.

This JavaScript register an event handler to the click event of every hyperlink in the container div tag of the grid using jQuery ‘live’ method (‘live’ method ensures that this event handler is applied to future hyperlinks that will be loaded using AJAX operations we well). This click event extracts the query string portion of the URL in each link, append it into action URL for “StudentGrid” action and then load the contents of the container div by sending AJAX request to that URL (using jQuery “load” method).

<script type="text/javascript">

$(document).ready(function () {
    $("#studentGrid a").live(‘click‘, function (event) {
        event.preventDefault();
        var href = $(this).attr("href");
        var queryString = href.substring(href.indexOf(‘?‘), href.length);
        var requestUrl =
            ‘@Url.Action(StudentController.StudentGridAction)‘ + queryString;
        $("#studentGrid").load(requestUrl);
    });
});

</script>

Thanks to jQuery authors, this simple script has perfectly solved the problem. Now, when a pagination or sorting link is clicked, the request is sent to StudentGrid action, that will only return the contents of the grid.

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。