目录

一、使用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的更多相关文章

  1. 【ASP.Net MVC】AspNet Mvc一些总结

    AspNet Mvc一些总结 RestaurantReview.cs using System; using System.Collections.Generic; using System.Comp ...

  2. 关于html、asp、php模板引擎、aspnet mvc、REST的一点思考

    先看我对REST的一点认识,下面是<rest实战> 这本书的序言文字:      在我刚刚开始从事解决计算问题的时候,业界就有很多人有一个愿望:将系统设计为能够被自由组合的组件.互联网(I ...

  3. 【ASP.Net MVC】在AspNet Mvc使用JQuery AutoComplete组件

    在AspNet Mvc使用JQuery AutoComplete组件 官方文档: http://api.jqueryui.com/autocomplete/#entry-examples 要使用JQu ...

  4. 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 ...

  5. AspNet MVC与T4,我定制的视图模板

    一. 遇到的问题 文章开头部分想先说一下自己的困惑,在用AspNet MVC时,完成Action的编写,然后添加一个视图,这个时候弹出一个添加视图的选项窗口,如下: 很熟悉吧,继续上面说的,我添加一个 ...

  6. 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 ...

  7. [译]ASP.NET:WebForms vs MVC

    原文示例(VS2012): 1.  Download Simple WebForm demo - 6.7 KB 2.  Download Simple MVC Demo demo - 1.5 MB 介 ...

  8. 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 ...

  9. 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": { " ...

  10. 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 ...

随机推荐

  1. 10)Java Error and Exception

      1>异常继承类        Error类和Exception类都继续自Throwable类      Error表示系统级的错误情况,如内存错误这样程序无法通过自身的处理再继续执行下去的情 ...

  2. VLC 重新编译第三方库的预编译包contrib

    VLC的引用了很多开源的第三方库,均放到VLC目录下的contrib中(本来开始编译是2.1.x以上版本,以前或以后可能会变化),在Windows版本编译中,contrib文件夹中仅仅下载VLC官网上 ...

  3. Mongodb 3.0 创建用户

    MongoDB 3.0 安全权限访问控制,在添加用户上面3.0版本和之前的版本有很大的区别,这里就说明下3.0的添加用户的方法. 创建第一个用户(该用户需要有grant权限,即:账号管理的授权权限) ...

  4. Learning Scrapy笔记(五)- Scrapy登录网站

    摘要:介绍了使用Scrapy登录简单网站的流程,不涉及验证码破解 简单登录 很多时候,你都会发现你需要爬取数据的网站都有一个登录机制,大多数情况下,都要求你输入正确的用户名和密码.现在就模拟这种情况, ...

  5. 第十九章 数据访问(In .net4.5) 之 处理数据

    1. 概述 本章介绍 数据库.Json和Xml.web services 三种介质上的数据操作. 2. 主要内容 2.1 数据库 ① 建立连接 .net平台中的数据连接类都继承自DbConnectio ...

  6. DB2数据库之间联邦

    现在有以下两个数据库:sample,QIN 需要在数据库QIN中访问sample中的表ACT 1.数据库编目 C:\Users\QIN>db2 catalog tcpip node OLIVER ...

  7. zip压缩

    package com.green.project.compress; import java.io.File;import java.io.FileInputStream;import java.i ...

  8. Node.js 异步模式浅析

    注:此文是node.js实战读后的总结. 在平常的脚本语言中都是同步进行的,比如php,服务器处理多个请求的方法就是并行这些脚本.多任务处理,多线程等等.但是这种处理方式也有一个问题:每一个进程或者线 ...

  9. Run ionic web app in nodejs

    首先需要express插件:sudo npm install express 将ionic project的www拷贝至wwwroot,新建server.js: var express = requi ...

  10. [iOS]深入浅出 iOS 之多线程 NSThread

    OS 支持多个层次的多线程 编程,层次越高的抽象程度越高,使用起来也越方便,也是苹果最推荐使用的方法.     下面简要说明这三种不同范式:  Thread 是这三种范式里面相对轻量级的,但也是使用起 ...