zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    通知:逆天异常库 V1.0版本支持下载了~~
    【源码】Word转PDF V1.0.1 小软件,供新手参考
    GitHub实战系列汇总篇
    GitHub实战系列~4.把github里面的库克隆到指定目录+日常使用 2015-12-11
    GitHub实战系列~3.提交github的时候过滤某些文件 2015-12-10
    Windows无法安装到这个磁盘。请确保在计算机的BIOS菜单中启用了磁盘控制器
    GitHub实战系列~2.把本地项目提交到github中 2015-12-10
    Git异常:fatal: could not create work tree dir 'XXX': No such file or directory
    GitHub实战系列~1.环境部署+创建第一个文件 2015-12-9
    肉肉好走,愿你在异界依旧快乐活泼
  • 原文地址:https://www.cnblogs.com/dufu/p/3960930.html
Copyright © 2011-2022 走看看