Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...