【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 ...
随机推荐
- Android EditText 不弹出输入法
当第一次进入一个activity的时候 一般是第一个edittext是默认选中的,但是该死的软键盘也一起弹出来了 那是相当的不美观哈!(#‵′)凸.为此, 本大人就去寻找在刚进入这个activity ...
- Oracle 查看相关优化器参数
select x.ksppinm name, y.ksppstvl value, y.ksppstdf isdefault, decode(bitand(y.ksppstvf, 7), 1, 'MOD ...
- C++基本数据类型解惑
记得刚学C语言的时候,对那些double,float,long,unsigned int各种混乱,基本是随便用,对数据类型没有一个整体的框架.最近学习<<C++ primer plus&g ...
- C#的编译
Windows上的编译 1:先将C:\Windows\Microsoft.NET\Framework\v3.5配置到系统环境变量的path里. 2:写C#代码 demo1.txt using Syst ...
- pure的bug记录2
<select id="stacked-state" style=" font-family: "Microsoft YaHei"; " ...
- IOS下载资源zip到本地然后读取
思路是 1.ios下载服务器上的zip资源包(图片,声音等经过zip压缩的资源包)到本地 2.解压zip到程序目录 3.从程序目录加载资源文件 一.下载zip资源 [cpp]-(NSString*)D ...
- Python核心编程--学习笔记--1--Python简介
本章介绍了Python的背景知识,包括什么是Python.Python的起源以及Python的一些关键特性. 1 什么是Python Python是一门优雅而健壮的编程语言,它继承了传统编译语言的强大 ...
- SegmentFault 2014黑客马拉松 北京 作品demo
1号作品展示——最熟悉的陌生人 app 利用录音(声纹识别)和照片来让好久不见的见面变得不那么尴尬. 2号作品展示——神奇魔镜 app 灵感来自通话<白雪公主>,穿越到今天的“魔镜”功能依 ...
- 使用dom4j技术对xml文件的基本操作
1.pojo类:Notice package com.green.notice.storage; import java.util.ArrayList; import java.util.List; ...
- poj 1564 Sum It Up
题目连接 http://poj.org/problem?id=1564 Sum It Up Description Given a specified total t and a list of n ...