目录

一、使用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. 关联参数(&的用法)

    <?php header("Content-Type:text/html;charset=gb2312"); function test1(&$a){ $a.=&qu ...

  2. How to using x++ code create GL journal[AX2012]

    static void FAN_GLImport(Args _args) { AxLedgerJournalTable header = new AxLedgerJournalTable(); AxL ...

  3. JqueryUI

    http://jqueryui.com/ http://www.runoob.com/jqueryui/jqueryui-tutorial.html

  4. 2016/09/21 java split用法

    public String[] split(String regex) 默认limit为0 public String[] split(String regex, int limit) 当limit& ...

  5. AngularJs记录学习03

    AngularJs的路由是一个组件,需要自己额外添加,在目录/src/ngRoute中 三个文件route.js,routeParams.js,ngView.js <html> <h ...

  6. XAML(4) - 标记扩展

    在为元素设置值时, 可以直接设置值, 但有时标记扩展非常有帮助.标记扩展包含花括号,其后是定义了标记扩展类型的字符串标志. 下面是一个Static Resource标记扩展: <Button N ...

  7. button与submit

    原文来自: http://blog.sina.com.cn/s/blog_693d183d0100uolj.html submit是button的一个特例,也是button的一种,它把提交这个动作自动 ...

  8. DB2递归查询

    斐波纳契数列,又称黄金分割数列,指的是这样一个数列:1.1.2.3.5.8.13.21.……在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n&g ...

  9. 019C#中使用移位运算符获取汉字编码值

    在进行移位运算时,当数值的二进制数每次向左移1位就相当于乘以2,当数值每次向右移一位就相当于除以2 private void button1_Click(object sender, EventArg ...

  10. C#(HTML)_小技巧_关于textbox框中不能输入HTML标签的解决方法(如输入“<p>”后,在提交表单时系统会崩溃)

    主要修改文件是config文件(Web.config): 1.在<pages>标签中添加属性:validateRequest="false" <pages val ...