【ASP.Net MVC】在AspNet Mvc使用Ajax
目录
一、使用System.Web.Mvc.Ajax
1.1 System.Web.Mvc.Ajax.BeginForm
1.2 System.Web.Mvc.Ajax.ActionLink
二、手工打造自己的“非介入式”Javascript”
一、使用System.Web.Mvc.Ajax

1.1 System.Web.Mvc.Ajax.BeginForm
第一步:用Ajax.BeginForm创建Form
@using (Ajax.BeginForm(
new AjaxOptions()
{
HttpMethod = "post",
Url = @Url.Action("Index","Reviews"),
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "restaurantList",
LoadingElementId = "loding",
LoadingElementDuration =
}))
{ <input type="search" name="searchItem"/>
<input type="submit" value="按名称搜索"/> }
最终生成的form如下:
<form id="form0" method="post"
data-ajax-url="/Reviews"
data-ajax-update="#restaurantList"
data-ajax-mode="replace"
data-ajax-method="post"
data-ajax-loading-duration=""
data-ajax-loading="#loding"
data-ajax="true"
action="/Reviews" novalidate="novalidate">
第二步:创建Ajax.BeginForm的new AjaxOptions()对象的Url指向的Action
new AjaxOptions()
{
...
Url = @Url.Action("Index","Reviews")
...
}
public ActionResult Index(string searchKey = null)
{
var model = _restaurantReviews.Where(r => searchKey == null || r.Name.ToLower().Contains(searchKey.ToLower().Trim()))
.OrderByDescending(r => r.Rating)
.Take()
.Select(r=>new RestaurantReview()
{
City = r.City,
Country = r.Country,
Id = r.Id,
Name = r.Name,
Rating = r.Rating
}).ToList(); if (Request.IsAjaxRequest())
{
System.Threading.Thread.Sleep( * );//模拟处理数据需要的时间 //return View(model)会返回整个页面,所以返回部分视图。
return PartialView("_RestaurantPatialView", model);
}
return View(model);
}
注意:
关于使用System.Web.Mvc.Ajax的说明:
Controller的Action方法:
()当显式添加[HttpPost],传给System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能为 "post",
()当显式添加[HttpGet],传给System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能为 "get",
()当都没有显式添加[HttpPost]和[HttpGet],传给System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod可以为 "get"也可以为"post",
第三步:添加要承载更新页面的html元素,
也就是添加添加AjaxOptionsd对象的UpdateTargetId 参数指定的Id为restaurantList的html元素:
这里在页面中添加:id为restaurantList的<div>:
<div id="restaurantList">...
</div>
第四步:(可选)为增强用户体验,添加AjaxOption对象的LoadingElementId参数指定的Id为loding的html元素:
new AjaxOptions()
{
....
LoadingElementId = "loding",
LoadingElementDuration =
}))
这里在页面中添加:id为loding的元素,添加了包含一个动态的刷新图片<div>:

cshtml文件中添加:
<div id="loding" hidden="hidden">
<img class="smallLoadingImg" src="@Url.Content("~/Content/images/loading.gif")" />
</div>
1.2 System.Web.Mvc.Ajax.ActionLink
System.Web.Mvc.Ajax.ActionLink与System.Web.Mvc.Ajax.BeginForm用法基本一致
第一步:使用System.Web.Mvc.Ajax.ActionLink创建超链接
@*@Html.ActionLink(item.Name, "Details", "Reviews",new{id = item.Id},new {@class ="isStar"})*@
@*<a class="isStar" href="@Url.Action("Details","Reviews", new {id = item.Id})">@item.Name</a>*@
@*使用Ajax的超链接*@
@{
var ajaxOptions = new AjaxOptions()
{
HttpMethod = "post",
//Url = @Url.Action(""),
UpdateTargetId = "renderBody",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "loding",
LoadingElementDuration =
};
@Ajax.ActionLink(item.Name, "Details", "Reviews", new { id = item.Id }, ajaxOptions, new {@class="isStar"})
}
对应生成的最终html为:
<a class="isStar"
href="/Reviews/Details/1"
data-ajax-update="#renderBody"
data-ajax-mode="replace"
data-ajax-method="post"
data-ajax-loading-duration=""
data-ajax-loading="#loding"
data-ajax="true">
第二步:定义出来响应超链接的Action:
/// <summary>
///关于使用System.Web.Mvc.Ajax的说明:
/// Controller的Action方法:
/// (1)当显式添加[HttpPost],传给System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能为 "post",
/// (2)当显式添加[HttpGet],传给System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能为 "get",
/// (3) 当都没有显式添加[HttpPost]和[HttpGet],传给System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod可以为 "get"也可以为"post",
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Details(int id=)
{
var model = (from r in _restaurantReviews
where r.Id == id
select r).FirstOrDefault(); if (Request.IsAjaxRequest())
{
return PartialView("_RestaurantDetails", model);
} return View(model);
}
第三步:定义承载更新部分的html元素:
<div id="renderBody">
....
</div>
第四步:(可选)为增强用户体验,添加AjaxOptionsd对象的LoadingElementId参数指定的Id为loding的html元素:
与1.1第四步相同。
二、手工打造自己的“非介入式”Javascript”
第一步:添加表单:
@* ---------------------------------------------------------
需要手工为Form添加些属性标签,用于锚点
模仿MVC框架的构建自己的“非介入式Javascript”模式
-------------------------------------------------------*@
<form method="post"
action="@Url.Action("Index")"
data-otf-ajax="true"
data-otf-ajax-updatetarget="#restaurantList">
<input type="search" name="searchItem" />
<input type="submit" value="按名称搜索" />
</form>
生成的form为:
<form data-otf-ajax-updatetarget="#restaurantList"
data-otf-ajax="true"
action="/Reviews"
method="post"
novalidate="novalidate">
第二步:添加处理表单的Action:
这里与1.1的第二步一样。
第三步:添加Js处理表单:
$(function () {
var ajaxFormSubmit = function() {
var $form = $(this);
var ajaxOption = {
type: $form.attr("method"),
url: $form.attr("action"),
data: $form.serialize()
};
$.ajax(ajaxOption).done(function(data) {
var updateTarget = $form.attr("data-otf-ajax-updatetarget");
var $updateTarget = $(updateTarget);
if ($updateTarget.length > ) {
var $returnHtml = $(data);
$updateTarget.empty().append(data);
$returnHtml.effect("highlight");
}
});
return false;
};
$("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
});
注意:
所谓的“非介入式Javascript”模式,是指
假如没有添加这一步,表单照样能被处理,只是没用到Ajax而已。 【The end】
【ASP.Net MVC】在AspNet Mvc使用Ajax的更多相关文章
- 【ASP.Net MVC】AspNet Mvc一些总结
AspNet Mvc一些总结 RestaurantReview.cs using System; using System.Collections.Generic; using System.Comp ...
- 关于html、asp、php模板引擎、aspnet mvc、REST的一点思考
先看我对REST的一点认识,下面是<rest实战> 这本书的序言文字: 在我刚刚开始从事解决计算问题的时候,业界就有很多人有一个愿望:将系统设计为能够被自由组合的组件.互联网(I ...
- 【ASP.Net MVC】在AspNet Mvc使用JQuery AutoComplete组件
在AspNet Mvc使用JQuery AutoComplete组件 官方文档: http://api.jqueryui.com/autocomplete/#entry-examples 要使用JQu ...
- VS2015突然报错————Encountered an unexpected error when attempting to resolve tag helper directive '@addTagHelper' with value 'Microsoft.AspNet.Mvc.Razor.TagHelpers.UrlResolutionTagHelper
Encountered an unexpected error when attempting to resolve tag helper directive '@addTagHelper' with ...
- AspNet MVC与T4,我定制的视图模板
一. 遇到的问题 文章开头部分想先说一下自己的困惑,在用AspNet MVC时,完成Action的编写,然后添加一个视图,这个时候弹出一个添加视图的选项窗口,如下: 很熟悉吧,继续上面说的,我添加一个 ...
- ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现
from:https://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/ 代码生成工具: https ...
- [译]ASP.NET:WebForms vs MVC
原文示例(VS2012): 1. Download Simple WebForm demo - 6.7 KB 2. Download Simple MVC Demo demo - 1.5 MB 介 ...
- the schema version of 'microsoft.aspnet.mvc' is incompatible with version of nuget
Nuget versioning issue with package restore http://stackoverflow.com/questions/12035976/nuget-versio ...
- Encountered an unexpected error when attempting to resolve tag helper directive '@addTagHelper' with value '"*, Microsoft.AspNet.Mvc.TagHelpers"'
project.json 配置: { "version": "1.0.0-*", "compilationOptions": { " ...
- Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5
https://developingsoftware.com/configuring-autofac-to-work-with-the-aspnet-identity-framework-in-mvc ...
随机推荐
- php或js判断网站访问者来自手机或者pc
php或js判断网站访问者来自手机或者pc机 2013年9月26日,在弄wtuonline的时候为了区分用户是来自手机版浏览器还是pc,针对不同平台选择不同的网站版本,最终总结如下: ...
- php网页,想弹出对话框, 消息框 简单代码
php网页,想弹出对话框, 消息框 简单代码 <?php echo "<script language=\"JavaScript\">alert(\&q ...
- book publisher and study
http://www.apress.com/ https://pragprog.com/ https://www.packtpub.com/ http://www.howzhi.com/
- jruby中的异常
先看看ruby中的异常知识: 异常处理raise 例子: raise raise "you lose" raise SyntaxError.new("invalid sy ...
- instanceof、==号、Objetc类
1)instanceof: 判断某个对象是否为某个类的实例,注意多态的运用,一个父类引用指向子类的对象,根据继承,子类就是父类,所以子类也可以看做是父类的一个实例. 形式:引用 instanceof ...
- Excel日期格式提取year
Excel日期格式提取year =TEXT(YEAR(C2),"0000")
- JS对文本框值的判断
JS判断只能是数字和小数点(摘录自其它资料,在此发表只为个人以后使用查找方便) 1.文本框只能输入数字(不包括小数点) <input onkeyup="this.value=this. ...
- Golang之ring.Ring的Link操作
ring.Ring 是一个环链. 其Link操作规则是: r.Link(s) => t = r.Next r.Next.Prev = s.Prev s.Prev.Next = r.Next r. ...
- wpa_supplicant测试
Android系统中对于WIFI的设置集成到了“设置”中,其实跟手动设置差不多.这里介绍下如何手动连接WIFI,以方便以后调试WIFI. 第一步要做的就是要加载WIFI模块驱动了.当然如果你的WIFI ...
- C++函数传指针和传引用的区别
从概念上讲.指针从本质上讲就是存放变量地址的一个变量,在逻辑上是独立的,它可以被改变,包括其所指向的地址的改变和其指向的地址中所存放的数据的改变. 而引用是一个别名,它在逻辑上不是独立的,它的存在具有 ...