2014-09-26 62 views
1

我不能理解關於aspx頁面處理循環的一些基本知識。請看下面這個簡單的例子。爲什麼IsPostBack在窗體上需要runat =「server」?

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 
    <title></title> 
</head> 

<body> 
    <div> 
     <form method="post"> 
      <textarea name="someContent" cols="35" rows="15"></textarea> 
      <input type="submit"/> 
     </form> 
    </div> 
</body> 
</html> 



<script runat="server"> 
    public void Page_Load() { 
     // The httpMethod is always set correctly to "GET" or "POST" 
     String httpMethod = HttpContext.Current.Request.HttpMethod; 

     if(IsPostBack) 
      DoSomething(); 
     else 
      DoSomethingElse(); 
    } 
</script> 

注意<形式>元件確實有中用runat = '服務器' 屬性。

第一次加載頁面時,Page_Load()觸發並且httpMethod變量設置爲「GET」,並且IsPostback屬性返回false,如預期的那樣。

當用戶點擊「提交」按鈕時,Page_Load()再次觸發並且httpMethod變量設置爲「POST」,因此ASP.NET管道系統顯然知道這是一個POST動詞;但是,IsPostBack屬性仍然返回false。這對我來說似乎很奇怪。我認爲如果httpMethod設置爲「POST」,IsPostBack將返回true。

如果我更改<表單>元素以包含runat ='server'屬性,事情會發生一些變化。現在,當用戶按下「submit」按鈕時,httpMethod變量被設置爲「POST」,與之前一樣,但現在IsPostBack返回true。

因爲我不需要訪問服務器上的<表單>元素,所以我看到沒有必要對它使用runat ='server'屬性。但由於某些原因,即使HttpContext.Current.Request.HttpMethod屬性返回了正確的值,而不管runat =是,但爲了使IsPostBack返回正確的值,runat ='server'必須出現在<的形式>上。 '服務器'屬性。

任何人都可以解釋爲什麼 RUNAT =「服務器」是必要的<形式>上正確地作出的IsPostBack工作?

注意:請注意,我不是問如何「做這個」或「做那個」。我的目標是理解「爲什麼」。

感謝

回答

0

頁檢查一些特殊領域(視圖狀態和回發事件),以確定是否請求是回發與否。
http://referencesource.microsoft.com/System.Web/R/ae07c23d0aba6bb9.html

這裏兩種形式造成的IsPostBack是真實的:

<%@ Page Language="C#" AutoEventWireup="true" %> 
<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
    <body> 

     <p><%= IsPostBack? "POSTBACK" : "NO POSTBACK" %></p> 

     <form id="form1" runat="server"> 
      <input type="submit" /> 
     </form> 

     <form id="form2" method="get"> 
      <input type="hidden" name="__EVENTTARGET" value="" /> 
      <input type="submit" /> 
     </form> 

    </body> 
</html> 

服務器控制的形式,只是增加了自動填充這些字段。