首页 文章

为什么IsPostBack在表单上需要runat =“server”?

提问于
浏览
1

我不能理解aspx页面处理周期的基本内容 . 请看下面这个简单的例子 .

<!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>

请注意,<form>元素没有runat = 'server'属性 .

第一次加载页面时,Page_Load()触发,httpMethod变量设置为“GET”,IsPostback属性返回false,全部按预期方式进行 .

当用户单击“提交”按钮时,Page_Load()再次触发,httpMethod变量设置为“POST”,因此ASP.NET管道显然知道这是一个POST动词;但是,IsPostBack属性仍然返回false . 这对我来说似乎很奇怪 . 我认为如果将httpMethod设置为“POST”,则IsPostBack将返回true .

如果我将<form>元素更改为包含runat ='server'属性,则会发生一些变化 . 现在,当用户按下“提交”按钮时,httpMethod变量设置为“POST”,就像之前一样,但现在IsPostBack返回true .

由于我不需要访问服务器上的<form>元素,因此我认为不需要在其上使用runat ='server'属性 . 但由于某种原因,必须在<form>上存在runat ='server'才能使IsPostBack返回正确的值,即使HttpContext.Current.Request.HttpMethod属性返回正确的值而不管runat = 'server'属性 .

任何人都可以解释为什么在<form>上运行= 'server'才能使IsPostBack正常工作?

注意:请注意,我不是在问“如何做”或“做那件事” . 我的目标是理解“为什么” .

谢谢

1 回答

  • 0

    页面检查几个特殊字段(viewstate和postback事件)以确定请求是否是回发 .
    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>
    

    服务器控制的表单只是自动添加和填充这些字段 .

相关问题