Ajax Action Link
先看下如何使用这些方法,首先保证页面加载了依赖的js库:
<script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
@H_404_0@一、效果
这样的效果便是点击超链接,从CS这个List方法返回的字符串,插入到id为tabledata的div中,在加载的过程中,id为loading的div会显示。应该说,这是一种非常常见的操作场景。在asp.net mvc的帮助下,我们不需要多写任何js代码就可以实现这一效果。下面来看下这是如何实现的。先看ActionLink生成了什么HTML代码:
<a data-ajax="true" data-ajax-loading="#loading"data-ajax-mode="replace"data-ajax-update="#tabledata"href="/cs/List?page=1"> 1</a>
1、Controller
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MyPeb.Mvc.Controllers { public class CsController : Controller { public ActionResult Index() { ViewBag.Title = "文章列表"; return View(); } public string List(int page) { return string.Format("第{0}页数据",page); } } }
2、Views
@{ Layout = null; int[] pages = new int[] {1,2,3,4,5 }; } <!DOCTYPE html> <script src="@Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> <html> <head> <title>@ViewBag.Title</title> </head> <body> <div>分页列表</div> <div> @foreach (var n in pages) { @Ajax.ActionLink(" "+n.ToString()+" ","List",new { page = n },new AjaxOptions { UpdateTargetId = "tabledata",LoadingElementId = "loading" }); } </div> <div id="loading"> 正在加载数据.... </div> <div id="tabledata"> </div> </body> </html>
@H_404_0@三、生成后的源码
<!DOCTYPE html> <script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script> <script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script> <html> <head> <title>文章列表</title> </head> <body> <div>分页列表</div> <div> <a data-ajax="true" data-ajax-loading="#loading" data-ajax-mode="replace" data-ajax-update="#tabledata" href="/cs/List?page=1"> 1 </a><a data-ajax="true" data-ajax-loading="#loading" data-ajax-mode="replace" data-ajax-update="#tabledata" href="/cs/List?page=2"> 2 </a><a data-ajax="true" data-ajax-loading="#loading" data-ajax-mode="replace" data-ajax-update="#tabledata" href="/cs/List?page=3"> 3 </a><a data-ajax="true" data-ajax-loading="#loading" data-ajax-mode="replace" data-ajax-update="#tabledata" href="/cs/List?page=4"> 4 </a><a data-ajax="true" data-ajax-loading="#loading" data-ajax-mode="replace" data-ajax-update="#tabledata" href="/cs/List?page=5"> 5 </a> </div> <div id="loading"> 正在加载数据.... </div> <div id="tabledata"> </div> </body> </html>
原文链接:https://www.f2er.com/ajax/165496.html