標籤:
視圖頁面的代碼如下:
<div id="ajax_search"> @using (Ajax.BeginForm( "Search",//Action "Test",//Controller new AjaxOptions { InsertionMode = InsertionMode.InsertAfter, HttpMethod = "GET", UpdateTargetId = "ajax_search", LoadingElementId = "loader",//服務端在執行操作時,展示一個進度給使用者看,相當於進度條 OnFailure = "Failed",//服務端執行失敗後調用的js方法 OnSuccess = "Success"//服務端執行成功後調用的js方法 })) { <input type="text" name="q" /> <input type="submit" value="搜尋" /> <img id="loader" style="display: none" src="~/Content/img/progress.gif" /> }</div>
控制器內要有一個執行非同步搜尋的Action,代碼如下:
//非同步搜尋 public ActionResult Search(string q) { // throw new Exception("故意讓你報錯"); // System.Threading.Thread.Sleep(3000); string msg = "你搜尋的關鍵詞:"+q; return PartialView("_search", msg); }
要新增一個分布視圖【也叫:部分視圖】到指定目錄裡面,用於展示非同步搜尋的結果。
當然跟Ajax.ActionLink 介紹的一樣,也需要引用jquery.unobtrusive-ajax.min.js到主版頁面裡面【_Layout.cshtml】
Ajax.BeginForm 非同步搜尋