目录

 

一、使用System.Web.Mvc.Ajax

  1.1 System.Web.Mvc.Ajax.BeginForm

  1.2 System.Web.Mvc.Ajax.ActionLink

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

 

 

一、使用System.Web.Mvc.Ajax

【ASP.Net MVC】在AspNet 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

相关文章: