【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 ...
随机推荐
- DOS下更改编码方式
使用CHCP命令,CHCP是Change Code Page的缩写. 936 简体中文GBK 437 美国英语 65001 UTF编码 如:chcp 65001则将dos窗口中的字符编码改为UTF编码 ...
- js控制div动起来
代码: <html> <head> <title>让div动的测试</title> <script language="javascri ...
- Python-Day12 Python mysql and ORM
一.Mysql数据库 1.什么是数据库? 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库, 每个数据库都有一个或多个不同的API用于创建,访问,管理,搜索和复制所保存的数据 ...
- [terry笔记]RMAN综合学习之配置
[terry笔记]RMAN综合学习之备份http://www.cnblogs.com/kkterry/p/3308405.html [terry笔记]RMAN综合学习之恢复 http://www.cn ...
- [terry笔记]Oracle会话追踪(一):SQL_TRACE&EVENT 10046
SQL_TRACE/10046 事件是 Oracle 提供的用于进行 SQL 跟踪的手段,在日常的数据库问题诊断和解决中是非常常用的方法.但其生成的trace文件需要tkprof工具生成一个可供人 ...
- python datetime date time详解
之前一直被datetime,date,time弄的有点乱,可能是因为看文档每太看明白,找到了两篇文章供大家阅读都是转载的,其中有些名词这里解释一下: 世界协调时间(Universal Time Coo ...
- makefile复习时发现的编写makefile规则注意事项
博客中关于makefile的博文数不胜数,比较经典的都很相似,下面这一片,很全面,只是很长,可以作为参考资料:http://blog.csdn.net/liang13664759/article/de ...
- Oracle用户,权限,角色以及登录管理 scoot 授权
Oracle用户,权限,角色以及登录管理 1. sys和system用户的区别 system用户只能用normal身份登陆em.除非你对它授予了sysdba的系统权限或者syspoer系统权限. sy ...
- [ios]ios-Demo4脱衣服/刮奖app-专业
普通版本完成的锯齿很严重 但是Ios系统中仅CGContextClearRect 并不存在cyclo等方法. 网上查了一些资料. 发现还是利用到了CG 中的Mask来实现效果图: 这种效果可以自定义画 ...
- Beyond Compare 4
Beyond Compare是一款不可多得的专业级的文件夹和文件对比工具.使用他可以很方便的对比出两个文件夹或者文件的不同之处.并把相差的每一个字节用颜色加以表示,查看方便.并且支持多种规则对比.