MVC之AJAX非同步表單

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   os   sp   for   java   

 

 曾經學習過AJAX,不是特別的熟悉,這次利用學習MVC的機會,好好的體驗了一把,非常感謝《MVC開發實戰》這本書,看了有兩三遍,才算對MVC整個啟動並執行機制有了一定的瞭解,下面來分享下我們經常在開發時用到到的非同步表單的操作。


 DEMO

  1.VIEW

   

<span style="font-size:18px;">@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>Index</title>    <script src="~/Scripts/jquery-1.8.2.min.js"></script>    <script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>    <script type="text/javascript">        function suc(resText) {            //            alert(resText);        }        function err(xhr) {            //失敗時執行操作,參數為ajaxrequest對象            alert(xhr.readyState);        }    </script>    <style type="text/css">        #imgLoad {            display: none;        }    </style></head><body>    @Ajax.ActionLink("串連文字", "GetDate", new AjaxOptions(){    HttpMethod = "post",    //更新的控制項id    UpdateTargetId = "contDiv",    //更新方式    InsertionMode = InsertionMode.Replace})    <div id="contDiv" style="border:1px solid #0094ff; width:400px;">我很好</div>    <h1>非同步表單:</h1>    @using (Ajax.BeginForm("GetDat", "Home", new AjaxOptions()    {        //提交請求的方法        HttpMethod = "post",        //成功時執行的非同步函數        OnSuccess = "suc",        OnFailure = "err",        //請求時載入的圖片        LoadingElementId = "imgLoad"    }))    {        <input type="text" name="txtName" />        <input type="submit" />        <div id="imgLoad">載入中~~~</div>    }</body></html></span>


  2.Controller

   

<span style="font-size:18px;">  /// <summary>    /// 控制器    /// </summary>    public class HomeController : Controller    {               public ActionResult Index()        {            return View();        }             /// <summary>        /// 非同步請求的方法,返回的是時間的內容對象        /// </summary>        /// <returns></returns>        public ActionResult GetDate()        {            System.Threading.Thread.Sleep(200);            return Content(DateTime.Now.ToString());        }    }</span>


 2.結果顯示


 3.程式碼分析

   1.非同步串連

     @Ajax.ActionLink()方法,經常用到的幾個參數在DEMO中已經體現,並且已經加入了詳細的注釋,主要用來實現非同步串連的操作。並且可以對返回的內容進行操作。

   2.非同步表單

     Ajax.BeginForm()方法,不得不說,在MVC中以後會經常用到這個方法,同上一樣,Demo有詳細的注釋,不再多說。比如我們在做一個登入功能的時候,就可以採取非同步表單。通過提交表單到後台,然後把返回的登入結果在現實到View中,挺方便的。



MVC之AJAX非同步表單

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.