Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronously sort GridView in ASP.NET MVC using Ajax

I'm using WebGrid to display data on client side, canSort: true is set.

The view code is:

@model UI.Models.TestModel

@if (Model.listTestModel != null)
{
    var grid = new WebGrid(Model.listTestModel,
    null,
    defaultSort: "ColumnA",
    rowsPerPage: 25,
    canPage: true,
    canSort: true
    );

    @grid.GetHtml(
     mode: WebGridPagerModes.All,

    columns: grid.Columns
            (
            grid.Column(columnName: "ColumnA", header: "ColumnA"),
            grid.Column(columnName: "ColumnB", header: "ColumnB")
            )
            )

}

I'm able to sort data by clicking column headers.

Problem:

How can someone asynchronously sort the WebGrid using Ajax?

like image 284
xameeramir Avatar asked Sep 26 '22 02:09

xameeramir


1 Answers

Thanks to Jamie Dunstan for pointing this out.

One need to make sure that the entire WebGrid code is inside a div with a unique id. Also, jQuery is referenced while Javascript is enabled.

 <div id='unique id goes here'>

@model UI.Models.TestModel

@if (Model.listTestModel != null)
{
    var grid = new WebGrid(Model.listTestModel,
    null,
    defaultSort: "ColumnA",
    rowsPerPage: 25,
    canPage: true,
    canSort: true,
    ajaxUpdateContainerId: "unique id goes here"
    );

    @grid.GetHtml(
     mode: WebGridPagerModes.All,

    columns: grid.Columns
            (
            grid.Column(columnName: "ColumnA", header: "ColumnA"),
            grid.Column(columnName: "ColumnB", header: "ColumnB")
            )
            )

}
<div>

<script>
    $(document).ready(function () {

  function updateGrid(e) {
    e.preventDefault();
    var url = $(this).attr('href');
    var grid = $(this).parents('.ajaxGrid');
    var id = grid.attr('id');
    grid.load(url + ' #' + id);
  };
  $('.ajaxGrid table thead tr a').on('click', updateGrid);
  $('.ajaxGrid table tfoot tr a').on('click', updateGrid);
 });
</script>

Notice that .live function is replaced with .on because of depreciation

like image 82
xameeramir Avatar answered Oct 12 '22 23:10

xameeramir