MVC項目開發中那些用到的知識點(Ajax.BeginForm)


Ajax.BeginForm可用於異步提交表單。

@using (Ajax.BeginForm("AjaxFormPost", "Home",
    new { ID="11", ClassName="FirstClass"},
    new AjaxOptions
    {
        HttpMethod = "POST",
        OnBegin="OnBeginPost()",
        OnComplete="OnEndPost()",
        OnSuccess="OnSuccessPost",
        InsertionMode = InsertionMode.Replace
    }))

 AjaxFormPost為Action,Home為控制器,new {ID=“11”,ClassName="FirstClass"}為路由參數即Url參數

AjaxOptions

1.HttpMethod提交表單的方式。

2.onBegin表單提交前 客戶端Js的操作。

3.OnSuccess表單提交后客戶端在此可以返回的操作

4.OnComplete表單提交完成后的操作

5.InsertionMode

    // 摘要:
    //     Enumerates the AJAX script insertion modes.
    public enum InsertionMode
    {
        // 摘要:
        //     Replace the element.
        Replace = 0,
        //
        // 摘要:
        //     Insert before the element.
        InsertBefore = 1,
        //
        // 摘要:
        //     Insert after the element.
        InsertAfter = 2,
    }

 

    <div id="content">
        <table>
            <tr>
                <td>
                    @Html.Label("lblName", "姓名")
                </td>
                <td>
                    @Html.TextBox("TxtName")
                </td>
            </tr>
            <tr>
                <td>
                    @Html.Label("lblAge", "年齡")
                </td>
                <td>
                    @Html.TextBox("TxtAge")
                </td>
            </tr>
        </table>
        <input type="submit" value="提交" />
        </div>

 這是簡單的表單控件,一個Name,一個Age,和一個提交按鈕。

下面來看一下對應Home控制器中Action的操作,此處只做測試,所以只進行取表單數據

        public string AjaxFormPost(string ID)
        {
            string ClassName = Request.QueryString["ClassName"];
            string Name = Request.Form["TxtName"];
            string Age = Request.Form["TxtAge"];
            return "姓名" + Name + "年齡" + Age;
        }

 ID為路由機制的參數。TxtName,TxtAge是通過表單進行獲取,前面設置為post方式,所以要用Request.Form的方式進行獲取相應的值。

然后返回一個字符串string,如果想在客戶端進行返回此字符串那么可以在上面AjaxOptions中的OnSuccess   

<script type="text/javascript">      function OnSuccessPost(e) {         alert(e+"提交成功!");     } </script>

 

當然如果想調用客戶端JavaScript還需要引用一個JavaScript庫。

 

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

這樣就可以進行調用測試

 
        

 

示例代碼

 

 


免責聲明!

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



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