佳木斯湛栽影视文化发展公司

主頁 > 知識(shí)庫 > 淺析Asp.net MVC 中Ajax的使用

淺析Asp.net MVC 中Ajax的使用

熱門標(biāo)簽:銀行業(yè)務(wù) 服務(wù)器配置 科大訊飛語音識(shí)別系統(tǒng) Mysql連接數(shù)設(shè)置 阿里云 Linux服務(wù)器 團(tuán)購網(wǎng)站 電子圍欄

一、使用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創(chuàng)建Form

  @using (Ajax.BeginForm(
    new AjaxOptions()
    {
      HttpMethod = "post",
      Url = @Url.Action("Index","Reviews"),
      InsertionMode = InsertionMode.Replace,
      UpdateTargetId = "restaurantList",
      LoadingElementId = "loding",
      LoadingElementDuration = 2000
    }))
  {
     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="2000"
    data-ajax-loading="#loding"
    data-ajax="true"
    action="/Reviews" novalidate="novalidate">

第二步:創(chuàng)建Ajax.BeginForm的new AjaxOptions()對(duì)象的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(100)
        .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(1000 * 3);//模擬處理數(shù)據(jù)需要的時(shí)間
        //return View(model)會(huì)返回整個(gè)頁面,所以返回部分視圖。
        return PartialView("_RestaurantPatialView", model);
      }
      return View(model);
    }

 注意:

    關(guān)于使用System.Web.Mvc.Ajax的說明:

       Controller的Action方法:

         (1)當(dāng)顯式添加[HttpPost],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能為 "post",

         (2)當(dāng)顯式添加[HttpGet],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能為 "get",

         (3)當(dāng)都沒有顯式添加[HttpPost]和[HttpGet],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod可以為 "get"也可以為"post",

      第三步:添加要承載更新頁面的html元素,

        也就是添加添加AjaxOptionsd對(duì)象的UpdateTargetId 參數(shù)指定的Id為restaurantList的html元素:

  這里在頁面中添加:id為restaurantList的div>:

div id="restaurantList">...
/div>

       第四步:(可選)為增強(qiáng)用戶體驗(yàn),添加AjaxOption對(duì)象的LoadingElementId參數(shù)指定的Id為loding的html元素:

  new AjaxOptions()
    {
      ....
      LoadingElementId = "loding",
      LoadingElementDuration = 2000
    }))

          這里在頁面中添加:id為loding的元素,添加了包含一個(gè)動(dòng)態(tài)的刷新圖片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創(chuàng)建超鏈接                

 @*@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 = 2000
              };
              @Ajax.ActionLink(item.Name, "Details", "Reviews", new { id = item.Id }, ajaxOptions, new {@class="isStar"}) 
            }

對(duì)應(yīng)生成的最終html為:

a class="isStar" 
  href="/Reviews/Details/1" 
  data-ajax-update="#renderBody" 
  data-ajax-mode="replace" 
  data-ajax-method="post" 
  data-ajax-loading-duration="2000" 
  data-ajax-loading="#loding" 
  data-ajax="true">

     第二步:定義出來響應(yīng)超鏈接的Action:

 /// summary>
    ///關(guān)于使用System.Web.Mvc.Ajax的說明:
    /// Controller的Action方法:
    ///  (1)當(dāng)顯式添加[HttpPost],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能為 "post",
    ///  (2)當(dāng)顯式添加[HttpGet],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能為 "get",
    ///   (3) 當(dāng)都沒有顯式添加[HttpPost]和[HttpGet],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod可以為 "get"也可以為"post",
    /// /summary>
    /// param name="id">/param>
    /// returns>/returns>
    public ActionResult Details(int id=1)
    {
      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>   

           第四步:(可選)為增強(qiáng)用戶體驗(yàn),添加AjaxOptionsd對(duì)象的LoadingElementId參數(shù)指定的Id為loding的html元素:

          與1.1第四步相同。

二、手工打造自己的“非介入式”Javascript”

第一步:添加表單:

@* ---------------------------------------------------------
     需要手工為Form添加些屬性標(biāo)簽,用于錨點(diǎn)
  模仿MVC框架的構(gòu)建自己的“非介入式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 > 0) {
        var $returnHtml = $(data);
        $updateTarget.empty().append(data);
        $returnHtml.effect("highlight");
      }      
    });
    return false;
  };
  $("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
});

注意:

  所謂的“非介入式Javascript”模式,是指假如沒有添加這一步,表單照樣能被處理,只是沒用到Ajax而已。

您可能感興趣的文章:
  • jQuery使用ajaxSubmit()提交表單示例
  • jquery中ajax使用error調(diào)試錯(cuò)誤的方法
  • 基于jquery的$.ajax async使用
  • jquery.ajax之beforeSend方法使用介紹
  • 使用jquery的ajax需要注意的地方dataType的設(shè)置
  • jquery序列化form表單使用ajax提交后處理返回的json數(shù)據(jù)
  • 跨域請(qǐng)求之jQuery的ajax jsonp的使用解惑
  • Ajax的使用代碼解析
  • Ajax的使用四大步驟
  • AJAX的使用方法詳解

標(biāo)簽:衢州 棗莊 蚌埠 大理 江蘇 萍鄉(xiāng) 廣元 衡水

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《淺析Asp.net MVC 中Ajax的使用》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    古田县| 安顺市| 浦东新区| 安仁县| 即墨市| 利津县| 鹤岗市| 新绛县| 固安县| 汝南县| 开鲁县| 兰考县| 萨迦县| 江都市| 南木林县| 江山市| 贺州市| 宜宾县| 大安市| 海盐县| 鹰潭市| 泰宁县| 响水县| 定兴县| 克什克腾旗| 来凤县| 泽普县| 文山县| 重庆市| 加查县| 屯昌县| 常州市| 玛曲县| 大竹县| 唐河县| 南开区| 临高县| 安泽县| 洛宁县| 贞丰县| 太保市|