ASP.NET\ASP.NET MVC表單提交遇到的問題結論


同步提交的兩種基本方式

  1,用type=“submit”按鈕。form沒有必要runat=“server”

 <form method="post" action="SubmitForm.aspx">
        id:<input type="text" id="txtId" name="txtId" /><br />
        name:<input type="text" id="txtName" name="txtName" /><br />
        <input type="submit" value="提交" />
    </form>

  2,用type=“button”。form沒有必要runat=“server”

javascript方式提交,不能type=“submit”:會造成想不到的問題。

<script>
        onload = function () {
            document.getElementById('btnsub').onclick = function () {
                var frm = document.getElementById('frm');
                if (frm) {
                    frm.submit();
                }
            }
        }
    </script> 
<form id="frm" method="post" action="SubmitForm.aspx">
        id:<input type="text" id="txtId" name="txtId" /><br />
        name:<input type="text" id="txtName" name="txtName" /><br />
        <input type="button" id="btnsub" value="提交" />
    </form>

注意:上述提交方式:form中沒有隱藏域,后置代碼中的ispostback永遠為false。

所以這些客戶端控件提交,假使沒有自己寫viewstate,后置代碼是不能用到ispostback。當然我們可以模擬隱藏域。

如果想使用ispostback,更為方便的方式,用form runat=“server”的表單。

 

runat=“server”提交

  1,form runat=“server”創建隱藏域,方便使用ispostback

<form id="form1"  runat="server" >
        <input id="btnsub" type="button" name="name" value="提交" />
    </form>

對應的源代碼

<form method="post" action="SubmitDemo4.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTEzNDM3NzkxOWRkFhrJ2htKdbAXWvYaKqbSR1DlJxfnPlLSZZ+sg4QDkgo=" />
</div>

<div class="aspNetHidden">

	<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="1D64C812" />
</div>
        <input id="btnsub" type="button" name="name" value="提交"  />
    </form>  

type=“button”的form,我們只能用javascript來提交。

<script>
        onload = function () {
            document.getElementById('btnsub').onclick = function () {
                var frm = document.getElementById('form1');
                if (frm) {
                    frm.submit();
                }
            }
        }

        </script>

后置代碼中可以用到ispostback,首次加載ispostback為false,post之后(點擊按鈕后)ispostback為true

 protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                var txtId = Request.Form["txtId"] ?? string.Empty;
                var txtName = Request.Form["txtName"] ?? string.Empty;
                Response.Write(txtId + txtName);
                Response.End();

            }
        }  

在后置代碼中,我們可以用ispostback,首次加載為false,post之后為true。

注意:form的runat=“server”屬性,幫我們做到的功能:加上隱藏域input type="hidden" name="__VIEWSTATE"和__VIEWSTATEGENERATOR

其中__VIEWSTATE就是后置代碼ispostback判斷真假的本質。

頁面首次加載,為get請求,__VIEWSTATE的input值不會被傳遞到后置代碼中。

當post提交時候,它會被提交到后台,我們只需在后置代碼中檢測這個input的值是否存在,不存在即是get請求,當然一般是首次加載,存在變是post回傳過來的。

 

  2,runat=“server”的第二個目的,在服務端拿到這個控件

它的目的:在后置代碼中,我們可以直接訪問並處理到對應的id的這個控件。

<script>
        onload = function () {
            document.getElementById('btnsub').onclick = function () {
                var frm = document.getElementById('<%= formclientID%>');
                if (frm) {
                    frm.submit();
                }
            }
        }
</script>

<form id="form1" runat="server">
    <div>
        <input type="button" id="btnsub" name="name" value="提交" runat="server" />
    </div>
    </form>

 后置代碼 :aspx和aspx.cs文件是繼承的關系,我們在后置代碼(基類)中定義一個變量為protect級別,這樣頁面可以拿到這個變量。

 public partial class runatserver : System.Web.UI.Page
    {
        protected string formclientID = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            formclientID = form1.ClientID;
            btnsub.Value = "改過的提交";
        }
    }

頁面顯示,顯示的是在后置代碼中被更改后的值,並非HTML中設置的value

           

 

服務器控件提交

也許你會用到服務器控件button,記得它一定在form runat=“server”中,否則報錯。類型“Button”的控件“Button1”必須放在具有 runat=server 的窗體標記內。

 <form id="form1" runat="server">
       <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </form>

頁面源代碼

 <form method="post" action="ServerControl.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTI0MTIwNDkwOWRk+uzHYLaWkTZXq5gbvwWQqLnBhSG8yeCI0Y0ZfO3Uiao=" />
</div>

<div class="aspNetHidden">

	<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="75E12176" />
	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAKMxJZ3e2e2T+pTyw/bgzf8zfg78Z8BXhXifTCAVkevd9GccaPBHHKDYQmgMf9k8Rs3iGzmicl8nAyLMrUQxTTv" />
</div>
       <input type="submit" name="Button1" value="Button" id="Button1" />
    </form>

 注意:本質是服務器button在頁面生成HTML:type=“submit”也就是我們上文提到的基本的提交方式第一種,如上文講到我們可以在后置代碼中拿到這個id。

  有了runat=“server”屬性為什么還要有服務器控件?

比如

 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

在設計中點擊之后,直接轉到后置代碼,創建click事件處理代碼。

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Response.Write("y");
        }

asp.net jQuery.ajax異步提交表單

<script src="js/jquery-1.4.1.min.js"></script>   
    <script>
        $(function () {
            $("#btnsub").click(function () {
                $.ajax({
                    type: "post",
                    url: "AsynSubmit.aspx/Page_Load",
                    //data: { username: $("#username").val(), content: $("#content").val() },
                    data:$("#form1").serialize(),
                    success: function (data) {
                alert(data); } }) }) }) </script>
 <form id="form1" runat="server">
        id:<input type="text" name="textID" value=" " /><br />
         Name:<input type="text" name="textName" value=" " /><br />
        <input id="btnsub" type="button" name="btnsub" value="異步提交" />
    </form>

后置代碼

            if (IsPostBack)
            {
                string id=Request.Form["textID"]??string.Empty;
                string Name=Request.Form["textName"]??string.Empty;
                Response.Write(id + Name);
                Response.End();
            }

注意:Response.End()的使用,不讓其返回其他流,只返回指定的數據就ok。因為默認會返回整個頁面的html。

  如何判斷一個請求是不是異步

第一個方法:請求的時候看瀏覽器的刷新按鈕,是否刷新。

第二個方法:查看這次請求的請求頭是否包含X-Requested-With:XMLHttpRequest,如果請求頭部還有這個標示,表示這次請求為異步請求。

 

不小心造成的問題  用到ajax,但是提交按鈕寫成了type=“submit”

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="js/jquery-1.4.1.min.js"></script>   
    <script>
        $(function () {
            $("#btnsub").click(function () {
                alert(1);
                $.ajax({
                    type: "post",
                    url: "AsynSubmit.aspx/Page_Load",
                    //data: { username: $("#username").val(), content: $("#content").val() },
                    data:$("#form1").serialize(),                  
                    success: function (data) {
                        $("#idd").text(data);
                    }

                })

            })
        })

    </script>
</head>
<body>
    <form id="form1" runat="server">
        id:<input type="text" name="textID" value=" " /><br />
         Name:<input type="text" name="textName" value=" " /><br />
        <input id="btnsub" type="submit" name="btnsub" value="異步提交" />
    </form>
    <div id="idd" style="width:200px;height:200px;background:red;"></div>
</body>
</html>

后置代碼

 protected void Page_Load(object sender, EventArgs e)
        {
            int count = 0;
            if (IsPostBack)
            {
                count++;
                string xrequest = Request.Headers["X-Requested-With"];
                if (xrequest != null)
                {
                    string id = Request.Form["textID"] ?? string.Empty;
                    string Name = Request.Form["textName"] ?? string.Empty;
                    Response.Write(id + Name);
                    //Response.End();//注意這個使用,不讓其返回整個頁面HTML
                   
                }
                else
                {
                    Response.Write("同步");

                }

            }
        } 

  注意+問題,求這個答案

后置代碼中打上斷點調試的過程中,並不是按照從上到下的執行,有時候會從下向上執行~~~因為同時發出了異步請求和同步請求,兩個請求同時到達。程序就出現紊亂。程序中的xrequest != null執行,表示請求是異步的。這樣便沒有什么意義。這種紊亂誰能解釋一下嗎?

MVC提交表單

   同步提交(頁面刷新)

 @using (Html.BeginForm())
    { <input type="text" name="name" value=" " />
        <input type="submit" value="提交"/>      
    }

頁面源代碼

<form action="/Form/index" method="post"> 
     <input type="text" name="name" value=" " /> <input type="submit" value="提交"/> </form>

  異步提交(請求頭也含有X-Requested-With:XMLHttpRequest)

1,引入隱士ajax腳本

2,表單里面的提交按鈕一定type=“submit”,否則沒有作用的。

  <script src="~/Scripts/jquery-1.7.1.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script>
        function success(data) {
            alert(data)
        }
    </script>


@using(Ajax.BeginForm(new AjaxOptions(){Confirm="ddddd", HttpMethod="post", OnSuccess="success" }))
    {
        <input type="text" name="name" value=" " />
        <input type="submit" value="提交"/>
    }

頁面源代碼

<form action="/Form/index" data-ajax="true" data-ajax-confirm="ddddd" data-ajax-method="post" data-ajax-success="success" id="form0" method="post">           <input type="text" name="name" value=" " />
        <input type="submit" value="提交"/>
</form>    

 


免責聲明!

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



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