Search in Help for developer site.

Saturday 13 May 2017

How to enable ajax pagination and sorting in asp net mvc webgrid

Enable ajax pagination and sorting in asp net mvc webgrid

1. Overview

We all know how to use WebGrid in ASP.NET MVC but when it comes to paging and sorting in WebGrid all developer goes with the traditional way or they will find Custom Paging, Client Side paging etc and even me also.

One day when i was developing an application where i need to use WebGrid then i found that WebGrid has a great feature for paging and sorting.

when you enable this feature the traditional synchronize paging and sorting shall be converted to asynchronize paging and sorting.

2. Enabling Ajax Paging and Sorting

First create a asp.net mvc project in visual studio and add a view and inside view create a WebGrid like below.

Index View Code:

@model List<SampleApp.Models.Employee>
<h2>Ajax Paging and Sorting in WebGrid </h2>

@using (Html.BeginForm())
{
    <div>
        <span id="loader" style="display:none;"> WebGrid is loading</span>
        <div id="gridDiv">
            @{
                var grid = new WebGrid(Model, rowsPerPage: 5, canPage: true, canSort: true, ajaxUpdateContainerId: "gridDiv");
                @grid.GetHtml();
                //In Get Html method you can customize your columns
            }
        </div>
    </div>
<script>
    $(document).ready(function () {
        $(document).ajaxStart(function () {
            $("#loader").show();
        }).ajaxStop(function () {
            $("#loader").hide();
        })
    })
</script>
}

As you can see that its a Normal WebGrid with a only difference of highlighted text:
ajaxUpdateContainerId :The value of the Html id attribute that is used to mark Html element that gets dynamic ajax updates that are associated with WebGrid instance.

So now when you click on any pagination link or sorting link then the whole page won't refresh instead of that only webgrid is going to refresh using asynchronous request.

To see the effect i have added ajaxStart and ajaxStop method that will show the loading text when an ajax request starts and hide loading text when it stops.
<script>
    $(document).ready(function () {
        $(document).ajaxStart(function () {
            $("#loader").show();
        }).ajaxStop(function () {
            $("#loader").hide();
        })
    })
</script>


3. Summary

We saw that how we can convert traditional synchronous pagination and sorting to asynchronous paging and sorting.
Using ajaxUpdateContainerId  option .
Do put your comments and queries in the comments section.




1 comment:

  1. Please, could you upload a complete example to download? I'm doing all of you mention but the whole page is refreshing. It would be very helpful. Thank you!

    ReplyDelete