【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 ...
随机推荐
- centos yum 安装问题
yum [Errno 256] No more mirrors to try 解决方法 输入下面的命令即可解决问题: yum clean all yum makecache 导致 centos安装软件 ...
- linux内核SPI总线驱动分析(二)(转)
简而言之,SPI驱动的编写分为: 1.spi_device就构建并注册 在板文件中添加spi_board_info,并在板文件的init函数中调用spi_register_board_info(s3 ...
- 在Silverlight宿主html页面添加按钮无法显示
在建silverlight应用程序时宿主html中嵌入的silverlight时出现的问题: 预想效果: 实际效果: silverlight填满整个page的所以无法显示html中其他的控件 解决办法 ...
- java遍历Map的几种方式
1.遍历map的几种方式:private Hashtable<String, String> emails = new Hashtable<String, String>(); ...
- SSIS包配置动态配置数据库连接
动态连接数据库便于维护 用SSIS包配置实现 1.控制流页签 - 右键 - 包配置 2.配置xml文件 3.指定连接属性:ServerName.UserName.Password 测试: 1.配置错误 ...
- VBA赋值给指定单元格
这是一个Range对象基本操作实例,对指定单元格赋值,然后使用弹窗获取值. 代码如下: Sub test1() Worksheets( MsgBox "工作表Sheet1内单元格A5中的值为 ...
- ORACLE-用户常用数据字典的查询使用方法
一.用户 查看当前用户的缺省表空间 SQL> select username,default_tablespace from user_users; USERNAME DEFAULT_TABLE ...
- ios中用drawRect方法绘图的时候设置颜色
设置画笔颜色可以直接 [[UIColor grayColor] set];就可以设置颜色.
- 时隔3年半Spring.NET 2.0终于正式Release了
一直很喜欢Spring.NET,不过2011年8月2日1.3.2正式release之后,再没有正式版本的release了. 直到4天前,Spring.NET 2.0 GA终于Release. http ...
- LoadRunner - 当DiscuzNT遇上了Loadrunner(下) (转发)
当DiscuzNT遇上了Loadrunner(下) 在之前的两篇文章中,基本上介绍了如何录制脚本和生成并发用户,同时还对测试报告中的几个图表做了简单的说明.今天这篇文章做为这个系列的最后一篇,将会介绍 ...