Reloading a Razor WebGrid after Ajax calls using a partial view

If you are using Razor and MVC you probably make some use of the built in controls in System.Web.Helpers. WebGrid, located in the Helpers assembly, was created for WebMatrix’s Razor Web Pages and landed itself nicely to Razor views in MVC.
WebGrid, much like ASP.NET’s ListView control, is designed to display a data driven HTML table on the screen. It has support for paging, sorting and column customization.
In this article, we will be taking a quick look at loading a WebGrid with data, both as a part of a page and as a standalone AJAX call. AJAX calls can occur after a page load or sort change and as a part of the interaction of a user with the data on the grid.
Let’s begin by making a view. The view will contain the body of the page rendered in the @RenderBody() section of the main layout. In our case the grid will reside in the index page and the index view will simply look like this:

@model IEnumerable<Deployments.Models.Deployment>
@{     ViewBag.Title = "Deployments";
} <h2>@ViewBag.Message</h2>
<p>     @Html.ActionLink("Request Deployment", "CreateDeployment")
</p>
@Html.Partial("DeploymentList", Model)

The Model is the data we wish to display and Html.Partial adds a partial view along with our grid.
We will take a look at the data later. First let’s display our grid. The grid resided in a partial view named DeploymentList:

@model IEnumerable<Deployments.Models.Deployment>

@{     var grid = new WebGrid(null, rowsPerPage: ViewBag.PageSize, ajaxUpdateContainerId: "deploymentsGrid", canSort: false);     grid.Bind(Model, rowCount: ViewBag.TotalRecords, autoSortAndPage: false);
}

A key part of the grid is ajaxUpdateContainerId. It signals the grid what container to update after an AJAX call. “deploymentsGrid” is a div surrounding the partial view and containing the Grid and any helper functions that will get updated in AJAX calls.
Now after we declared the grid we can look at the controller. The grid sends some query string parameters for paging and sorting by default. Since our grid has pagination enabled, our controller should be able to deal with an optional page parameter.

private DeploymentsEntities context = new DeploymentsEntities();         private int pageSize = 10;         public ActionResult Index(int? page)         {             ViewBag.Message = "Deployments";             ViewBag.PageSize = pageSize;             ViewBag.TotalRecords = context.Deployments.Count(d => d.Active == true);             var model = context.Deployments                 .Include("Website")                 .Include("Environment")                 .OrderByDescending(d => d.DeploymentID)                 .Where(d => d.Active == true)                 .Skip(((page.HasValue ? page.Value : 1) - 1) * pageSize)                 .Take(pageSize);             if (Request.IsAjaxRequest())                 return PartialView("DeploymentList", model);             else                 return View(model);         }

As you can see, when our controller is invoked by an AJAX request, we do not need to return the entire index view. We can simply return the partial view containing the grid. Retuning a partial view will make sure only the HTML we need to update is actually being generated.
This is the rest of the grid view:

<div id="deploymentsGrid">  @grid.GetHtml(         columns: grid.Columns(                     grid.Column("Website.WebsiteName", header: "Website"),                     grid.Column("Environment.EnvironmentName", header: "From"),                     grid.Column("Environment1.EnvironmentName", header: "To"),                     grid.Column("RequestedBy", header: "Requested By"),                     grid.Column("RequestedDate", header: "Requested Time"),                     grid.Column("ExecutedBy", header: "Executed By"),                     grid.Column("ExecutedDate", header: "Executed Time"),                     grid.Column("WebsiteSync", header: "Website", format: (item) => (item.WebsiteSync) ? Html.Raw("<img src='/images/active.png' />") :                         Html.Raw("<img src='/images/inactive.png' />")),                     grid.Column("DatabaseSync", header: "Database", format: (item) => (item.DatabaseSync) ? Html.Raw("<img src='/images/active.png' />") :                         Html.Raw("<img src='/images/inactive.png' />")),                     grid.Column("Comments", header: "Comments"),                     grid.Column("", header: "Done", format: (item) => (string.IsNullOrWhiteSpace(item.ExecutedBy)) ?                          @Ajax.ActionLink("Done", "Done", new { id = item.DeploymentID },                          new AjaxOptions() {                             Confirm = "Did you check your work?",                             HttpMethod = "Get",                             OnSuccess = "updateGrid()"                         }) :                         Html.Raw("<a href='" + item.Environment1.WebsiteURL + "' target='_new'>View</a>"))                         )               )

<script type="text/javascript">     function updateGrid() {         @Html.Raw(HttpUtility.HtmlDecode(grid.GetContainerUpdateScript("/?page=" + (grid.PageIndex + 1)).ToString()))     }
</script>
</div>

If you read through the code, you probably noticed the @Ajax.ActionLink “Done”. This is a simple GET call along with a parameter containing the ID of the record we wish to update. The interesting part about it is the OnSuccess call. This is a JavaScript call that is made when the ActionLink returns successfully.
Since our update operation succeeded, we will go ahead and update the grid:

@Html.Raw(HttpUtility.HtmlDecode(grid.GetContainerUpdateScript("/?page=" + (grid.PageIndex + 1)).ToString()))

GetContainerUpdateScript is built into the grid. If you view the source of the page, you will probably find it in the JavaScript onClick events of your pager. We are simply calling it again, along with the current grid page in order to update the container div.
As you can tell, WebGrid has some great web 2.0 functionality out of the box and can help you speed up Razor development.

[webgrid] – Ajax – (Reloading a Razor WebGrid after Ajax calls using a partial view)的更多相关文章

  1. ASP.NET Core Razor中处理Ajax请求

    如何ASP.NET Core Razor中处理Ajax请求 在ASP.NET Core Razor(以下简称Razor)刚出来的时候,看了一下官方的文档,一直没怎么用过.今天闲来无事,准备用Rozor ...

  2. .NET Core Razor Pages中ajax get和post的使用

    ASP.NET Core Razor Pages Web项目大部分情况下使用继承与PageModel中的方法直接调用就可以(asp-page),但是有些时候需要使用ajax调用,更方便些.那么如何使用 ...

  3. 对jquery的ajax进行二次封装以及ajax缓存代理组件:AjaxCache

    虽然jquery的较新的api已经很好用了, 但是在实际工作还是有做二次封装的必要,好处有:1,二次封装后的API更加简洁,更符合个人的使用习惯:2,可以对ajax操作做一些统一处理,比如追加随机数或 ...

  4. 原生态AJAX详解和jquery对AJAX的封装

    AJAX: A :Asynchronous [eI`sinkrenes] 异步 J :JavaScript    JavaScript脚本语言 A: And X :XML 可扩展标记语言 AJAX现在 ...

  5. ajax学习笔记(原生js的ajax)

    ajax是一个与服务器端语言无关的技术,可以使用在任何语言环境下的web项目(如JSP,PHP,ASP等). ajax优点: 1) 页面无刷新的动态数据交互 2) 局部刷新页面 3) 界面的美观 4) ...

  6. 来了解一下Ajax是什么?Ajax的原理?Ajax与传统Web比较?Ajax的优缺点?Ajax的Post与Get比较

    一.什么是Ajax Ajax(Asynchronous Java and XML的缩写)是一种异步请求数据的web开发技术,对于改善用户的体验和页面性能很有帮助.简单地说,在不需要重新刷新页面的情况下 ...

  7. Ajax轮询——“定时的通过Ajax查询服务端”

    Ajax轮询——"定时的通过Ajax查询服务端". 概念: 轮询(polling):客户端按规定时间定时像服务端发送ajax请求,服务器接到请求后马上返回响应信息并关闭连接. 百闻 ...

  8. javascript AJAX简单原理及什么是ajax

    AJAX简单原理供初学者理解 AJAX的原理: Ajax的原理简单来说通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面.这其 ...

  9. 客户端调用服务器端方法——ASP.NET AJAX(Atlas)、Anthem.NET和Ajax.NET Professional实现之小小比较

    前几天曾经发过一篇<ASP.NET AJAX(Atlas)和Anthem.NET——管中窥豹般小小比较>,Jeffrey Zhao说用ASP.NET AJAX中的UpdatePanel似乎 ...

随机推荐

  1. js学习笔记3---自定义属性

    1.自定义属性-----JS可以为任何 HTML元素 添加 任意个 自定义属性 方法:元素.属性 = 属性值 如:aBtn[0].abc = 123; 2.添加索引值,匹配数组 for(i=0; i& ...

  2. 【CodeForces 697B】Barnicle

    对科学计数法表示的数,输出其10进制的形式. c++来做,需要考虑这些细节: 当b==0,d==0时,只输出a. 当不需要补零的情况有两种: 一种是刚好是整数,只输出a(注意1.0e1的情况是输出1) ...

  3. 【转】Handler学习笔记(一)

    一.Handler的定义: Handler主要接收子线程发送的数据, 并用此数据配合主线程更新UI,用来跟UI主线程交互用.比如可以用handler发送一个message,然后在handler的线程中 ...

  4. Redis集合-Set

    sadd 向一个Set中添加数据 127.0.0.1:6379> sadd set01 1 1 2 2 3 3 (integer) 3127.0.0.1:6379> SMEMBERS se ...

  5. js-JavaScript高级程序设计学习笔记3

    第五章 引用类型 1.使用new操作符和Date构造函数创建日期对象. 2.创建特定日期有两个方法--Date.parse()和Date.UTC().后者小时数为0时显示时间是8点,应该是因为本地是东 ...

  6. 【BZOJ-3252】攻略 DFS序 + 线段树 + 贪心

    3252: 攻略 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 339  Solved: 130[Submit][Status][Discuss] D ...

  7. eclipse无法识别javax.servlet.*的问题

    这个问题对应的jar包为servlet-api.jar,默认jdk是没有这个包,需要在web容器上找到这个包,比如我用的是tomcat,那么可以在:“\Tomcat 7.0\lib\servlet-a ...

  8. [IOS 实现TabBar在Push后的隐藏 以及 两级Tabbar的切换]

    翻了好多网页都没找到资料,自己试了下终于成功了,遂分享一下. 1.实现TabBar在Push后的隐藏 假如结构是这样 NavController->A->B,我们想要实现在A里有Tabba ...

  9. 巧妙的重载魔术方法__call()

    工作半年了,感觉这半年学到的东西比大学四年学到的还要多,主要原因是心静下来了,目标也明确了,不会去整天的和游戏纠缠在一起了.大学时候其实也意识到了玩游戏会影响自己的正常学习和工作的,但是一直控制不了自 ...

  10. centos安装CODEBLOCKS

    装了好多次系统,每次装的时候都有要在网上各种查,太麻烦了.所以决定记录一下,以后用到的时候会方便一些.当然,本文来源于网络,取百家之长,最重要的是本人已验证过,说明对本系统是可行的. 在CentOS7 ...