[webgrid] – Ajax – (Reloading a Razor WebGrid after Ajax calls using a partial view)

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.

时间: 2024-10-23 11:21:27

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

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

ASP.NET Core Razor Pages Web项目大部分情况下使用继承与PageModel中的方法直接调用就可以(asp-page),但是有些时候需要使用ajax调用,更方便些.那么如何使用ajax调用呢?? 1.Razor Pages普通页面的跳转 <a asp-page="About">About</a> <form asp-page="./Index" method="get"> <div

框架基础:关于ajax设计方案(三)---集成ajax上传技术

之前发布了ajax的通用解决方案,核心的ajax发布请求,以及集成了轮询.这次去外国网站逛逛,然后发现了ajax level2的上传文件,所以就有了把ajax的上传文件集成进去的想法,ajax方案的level2的改进就不介绍了,不清楚的可到前几篇博客去看看.我们直接切入主题. 概念介绍: 1. js的FormData:js中在新的版本中已经支持了FormData对象,可以初始化一个空的form,或者初始化已经存在的form,浏览器测试代码. 2. 浏览器的支持:浏览器已支持input=file的

框架基础:ajax设计方案(三)---集成ajax上传技术

之前发布了ajax的通用解决方案,核心的ajax发布请求,以及集成了轮询.这次去外国网站逛逛,然后发现了ajax level2的上传文件,所以就有了把ajax的上传文件集成进去的想法,ajax方案的level2的改进就不介绍了,不清楚的可到前几篇博客去看看.我们直接切入主题. 概念介绍: 1. js的FormData:js中在新的版本中已经支持了FormData对象,可以初始化一个空的form,或者初始化已经存在的form,浏览器测试代码. 2. 浏览器的支持:浏览器已支持input=file的

Ajax工作原理以及常用的Ajax框架

1,关于同步和异步 异步传输是面向字符的传输,它的单位是字符:而同步传输是面向比特的传输,它的单位是桢,它传输的时候要求接受方和发送方的时钟是保持一致的. ajax可以提升用户体验,它是利用异步请求方式的.打个比方,如果现在你家里所在的小区因 某种情况而面临停水,现在有关部门公布了两种方案,一是完全停水8个小时,在这8个小时内完全停水,8个小时后恢复正常.二是不完全停水10 个小时,在这10个小时内水没有完全断,只是流量比原来小了很多,在10个小时后恢复正常流量,那么,如果是你你会选择哪种方式呢

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

Ajax轮询——"定时的通过Ajax查询服务端". 概念: 轮询(polling):客户端按规定时间定时像服务端发送ajax请求,服务器接到请求后马上返回响应信息并关闭连接. 百闻不如一见,来段代码相信你一看就明白 //为了让同学们都明白,我用了最简单的实现方法,同学们懂了原理后可以自行衍生: Reception.html //前端代码 <html> <head> <title></title> <script src="

AJAX &amp; JavaScript Barcode Generator集成到AJAX Web应用程序创建条形码图像

AJAX & JavaScript Barcode Generator是原生的JavaScript,用于创建条形码图像,它可以很容易地集成到AJAX Web应用程序,Oracle报表和HTML中.因为它是原生的JavaScript ,所以不需要安装任何额外的组件,字体或插件来创建条形码,它还是功能完善的JavaScript条形码生成空控件. 具体功能: 多种条形码类型被一个单个的产品所支持. 多地区兼容性-本产品兼容了所有的语言和地区设置,包括Windows的双字节版本,如用于中国和日本,以及亚

JavaScript之Ajax-2 Ajax(使用Ajax发送get请求、使用Ajax发送post请求)

一.使用Ajax发送get请求 发送异步请求的步骤 - 获取Ajax对象:获取 XMLHttpRequest对象实例 - 创建请求:调用XMLHTTPRequest对象的open方法 - 设置回调函数:为Ajax对象的 onreadystatechange事件设定响应函数 - 发送请求:调用Ajax对象的send方法 - 获取Ajax对象     - 创建请求 - 注意: - true:表示发送异步请求(当Ajax对象发送请求时,用户仍然可以对当前页面做其它的操作) - false:表示发送同步

JavaScript之Ajax-6 Ajax的增强操作(jQuery对Ajax的支持、表单操作)

一.jQuery对Ajax的支持 load() - 作用: 将服务器返回的数据字节添加到符合要求的节点之上 - 用法: $obj.load(请求地址,请求参数) - 请求参数 - "username=tom&age=22" - {'username':'tom','age':22} - 有请求参数时,load方法发送POST请求,否则发送GET请求 get() - 作用: 发送GET类型的请求 - 用法: $.get(请求地址,请求参数,回调函数,服务器返回的数据类型) - 说

[开源] jQuery 插件,利用‘localStorage’ 对 jQuery AJAX进行缓存,优化页面ajax请求

jquery-ajax-cache 源码地址:https://github.com/WQTeam/jquery-ajax-cache jQuery插件——利用‘localStorage’ 和 ‘sessionStorage’ 对 jQuery AJAX 请求进行缓存. 首先说明下在什么场景下需要用到缓存ajax请求到localstorage中.都知道浏览器本身对http请求就是有缓存策略的,但是这种缓存方式两个缺陷:1.只能缓存get请求 2.同时缓存的设置都在后端响应的报文头部指定.(PS:现