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.

时间: 2024-10-12 08:08:24

ASP.NET MVC WebGrid – Performing true AJAX pagination and sorting 【转】的相关文章

Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call

http://stackoverflow.com/questions/15466597/rendering-a-simple-asp-net-mvc-partialview-using-jquery-ajax-post-call Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call,布布扣,bubuko.com

转:ASP.Net MVC:校验、AJAX与过滤器

原文地址:http://blog.jobbole.com/85005/ 一.校验 — 表单不是你想提想提就能提 1.1 DataAnnotations(数据注解) 位于 System.ComponentModel.DataAnnotations 命名空间中的特性指定对数据模型中的各个字段的验证.这些特性用于定义常见的验证模式,例如范围检查和必填字段.而 DataAnnotations 特性使 MVC 能够提供客户端和服务器验证检查,使你无需进行额外的编码来控制数据的有效. 通过为模型类增加数据描

通过ASP.NET MVC框架 + 原生JavaScript + Ajax + SQL SERVER 实现一个简单的有论坛功能的网站(有通过iis发布的例子)

ASP.NET MVC. M 为Model模型层, V 为View视图层, C 为Controller控制层.要想使用MVC框架来写网站就需要了解M V C 的作用分别为哪些.给大家简单的介绍一下: 1.当你的这个网站要与数据库交互的时候,你可以使用EF创建一个数据库模型,也可以用类存放你所需交互的字段数据.我们往往把这类文件放在model层. 2.view层,存放前端网页的. 3.controller层实现前端网页功能的,在这个层里面我们编写的方法称为action. www.lazyfitne

ASP.NET MVC中如何以ajax的方式在View和Action中传递数据

前言:写这篇随笔的时候,在url上漏写了斜线,找了好久错误,整个人都很不好.#我是猪系列 背景:之前介绍过一篇如何构建ASP.NET MVC4&JQuery&AJax&JSon示例,这一篇单独讲解如何在View和Action间传递并处理数据. 1,前台HTML代码: 1 <div> 2 <button type="button" id="btn">从视图向控制器中传递数据</button> 3 <p

ASP.NET MVC+JQuery母版页的Ajax提交问题

<pre name="code" class="javascript">Ajax内容: $(document).ready(function () { $(function () { $("#submit").click(function () { var name = $("#log").val(); var pwd = $("#pwd").val(); if (name.length ==

ASP.NET MVC 4 之 Jquery Ajax

//前台界面,一个下拉框,一根文本框 <select id="SEX">     <option>男</option>     <option>女</option>     <option>未知</option> </select> <input id ="DESC"  type="text"/> //页面引入js <script t

Asp.Net MVC Ajax

将ASP.NET MVC中的form提交改为ajax提交 在ASP.NET MVC视图中通过 @using (Html.BeginForm()) 产生的是form表单提交代码,可以用javascript代码截获这个form提交,改为ajax提交,示例代码如下: 代码来自:http://www.cnblogs.com/dudu/archive/2011/12/07/asp_net_mvc_form_ajax.html $('#form1').submit(function () {    if (

ASP.NET MVC 入门11、使用AJAX

asp.net mvc 支持微软自身Ajax 和 JQuery框架 asp.net mvc View视图可以理解为 一个包含"<%%>"变量引和的模板. Script与HTML优雅分离参见: http://www.cnblogs.com/QLeelulu/archive/2008/10/22/1317214.html ASP.NET MVC 入门11.使用AJAX

ASP.NET MVC Ajax 伪造请求

1.前言 CSRF(Cross-site request forgery)跨站请求伪造,ASP.NET MVC 应用通过使用AJAX请求来提升用户体验,浏览器开发者工具可以一览众山小,就很容易伪造了请求对应用进行攻击,从而泄露核心数据,导致安全问题.微软自带AntiForgeryToken可以解决,而且语法简单(AJAX请求发起时传递给后台一个字符串,然后在Filter中进行校验) 2.场景如下 为了验证一个来自form post请求,还需要在目标action上增加自定义[AntiForgery