浅析Asp.net MVC 中Ajax的使用

2019-09-14 07:05:24王振洲

        也就是添加添加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);
    }