【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 = 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">

 

第二步:創建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(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);//模擬處理數據需要的時間

                //return View(model)會返回整個頁面,所以返回部分視圖。
                return PartialView("_RestaurantPatialView", model);
            }
            return View(model);
        }
View Code

 

 注意:

    關於使用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",

     

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

        也就是添加添加AjaxOptionsd對象的UpdateTargetId 參數指定的Id為restaurantList的html元素:

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

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

 

       第四步:(可選)為增強用戶體驗,添加AjaxOption對象的LoadingElementId參數指定的Id為loding的html元素:

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

          這里在頁面中添加: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 = 2000
                            };
                            @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="2000"
  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=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>         

 

                   第四步:(可選)為增強用戶體驗,添加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 > 0) {

                var $returnHtml = $(data);
                $updateTarget.empty().append(data);
                $returnHtml.effect("highlight");
            }            
        });

        return false;
    };

    $("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
});       

 

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







【The end】




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM