none
.网页上的TextBox并没有设AutoPostBack为true,为什么它能够执行事件处理程序 RRS feed

  • 问题

  • 1.网页上的TextBox并没有设AutoPostBack为true,为什么它能够执行事件处理程序?
    2.我在Default.aspx页面如果点右键选“在浏览器中查看”,在出现的页面上操作一切

    正常;如果通过按F5启动调试,在出现的页面上操作,会出现异常。
    异常位置在CallBackHelper类的HandleError的“hr.StatusCode = 200;”这里。
    报出的异常信息:“服务器无法在已发送 HTTP 标头之后设置状态。”
    为什么同样的代码不同的运行方式,执行的结果不一样呢?

    以下为部分代码:

    CallBackHelper类:

    public class CallBackHelper
        {
            private CallBackHelper() { }

            public static bool IsCallBack
            {
                get
                {
                    HttpRequest hr = CallBackHelper.GetHttpRequest();
                    return hr.Params["IsCallBack"] != null;
                }
            }

            public static void Write(string Text)
            {
                HttpResponse hr = CallBackHelper.GetHttpResponse();

                hr.Clear();
                hr.StatusCode = 200;
                hr.StatusDescription = "OK";
                hr.Write(Text);
                hr.Flush();
                hr.End();
            }

            public static void HandleError(Exception e)
            {
                HttpResponse hr = CallBackHelper.GetHttpResponse();

                hr.Clear();
                hr.StatusCode = 200;
                hr.StatusDescription = "ERROR";
                hr.Write(e.ToString());
                hr.Flush();
                hr.End();
            }

            private static HttpResponse GetHttpResponse()
            {
                HttpResponse hr = null;
                try
                {
                    hr = System.Web.HttpContext.Current.Response;
                }
                catch (NullReferenceException nre)
                {
                    throw new Exception("CallBackHelper could not access current HttpResponse object", nre);
                }

                return hr;
            }

            private static HttpRequest GetHttpRequest()
            {
                HttpRequest hr = null;
                try
                {
                    hr = System.Web.HttpContext.Current.Request;
                }
                catch (NullReferenceException nre)
                {
                    throw new Exception("CallBackHelper could not access current HttpRequest object", nre);
                }

                return hr;
            }
        }

    CallBackObject.js文件:

    function CallBackObject() {
        this.XmlHttp = this.GetHttpObject();
    }

    CallBackObject.prototype.GetHttpObject = function() {
        var xmlhttp;
        /*@cc_on
        @if (@_jscript_version >= 5)
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
        @else
      xmlhttp = false;
      @end
        @*/
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
            try {
                xmlhttp = new XMLHttpRequest();
            } catch (e) {
                xmlhttp = false;
            }
        }
        return xmlhttp;
    }

    CallBackObject.prototype.DoCallBack = function(eventTarget, eventArgument) {
        var theData = '';
        var theform = document.forms[0];
        var thePage = window.location.pathname + window.location.search;
        var eName = '';

        theData = '__EVENTTARGET=' + escape(eventTarget.split("$").join(":")) + '&';
        theData += '__EVENTARGUMENT=' + eventArgument + '&';
        theData += '__VIEWSTATE=' + escape(theform.__VIEWSTATE.value).replace(new RegExp('\\+', 'g'), '%2b') + '&';
        theData += 'IsCallBack=true&';
        for (var i = 0; i < theform.elements.length; i++) {
            eName = theform.elements[i].name;
            if (eName && eName != '') {
                if (eName == '__EVENTTARGET' || eName == '__EVENTARGUMENT' || eName == '__VIEWSTATE') {
                    // Do Nothing
                }
                else {
                    theData = theData + escape(eName.split("$").join(":")) + '=' + theform.elements[i].value;
                    if (i != theform.elements.length - 1)
                        theData = theData + '&';
                }
            }
        }

        if (this.XmlHttp) {
            if (this.XmlHttp.readyState == 4 || this.XmlHttp.readyState == 0) {
                var oThis = this;
                this.XmlHttp.open('POST', thePage, true);
                this.XmlHttp.onreadystatechange = function() { oThis.ReadyStateChange(); };
                this.XmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                this.XmlHttp.send(theData);
            }
        }
    }

    CallBackObject.prototype.AbortCallBack = function() {
        if (this.XmlHttp)
            this.XmlHttp.abort();
    }

    CallBackObject.prototype.OnLoading = function() {
        // Loading
    }

    CallBackObject.prototype.OnLoaded = function() {
        // Loaded
    }

    CallBackObject.prototype.OnInteractive = function() {
        // Interactive
    }

    CallBackObject.prototype.OnComplete = function(responseText, responseXml) {
        // Complete
    }

    CallBackObject.prototype.OnAbort = function() {
        // Abort
    }

    CallBackObject.prototype.OnError = function(status, statusText) {
        // Error
    }

    CallBackObject.prototype.ReadyStateChange = function() {
        if (this.XmlHttp.readyState == 1) {
            this.OnLoading();
        }
        else if (this.XmlHttp.readyState == 2) {
            this.OnLoaded();
        }
        else if (this.XmlHttp.readyState == 3) {
            this.OnInteractive();
        }
        else if (this.XmlHttp.readyState == 4) {
            if (this.XmlHttp.status == 0)
                this.OnAbort();
            else if (this.XmlHttp.status == 200 && this.XmlHttp.statusText == "OK")
                this.OnComplete(this.XmlHttp.responseText, this.XmlHttp.responseXML);
            else
                this.OnError(this.XmlHttp.status, this.XmlHttp.statusText, this.XmlHttp.responseText);
        }
    }
    页面文件:

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title></title>
        <script language="jscript" type="text/jscript" src="CallBackObject.js"></script>
        <script language="jscript" type="text/jscript">
            var Cbo = new CallBackObject();
            Cbo.OnComplete = Cbo_Complete;
            Cbo.OnError = Cbo_Error;

            function CheckUsername(Username) {
                var msg = document.getElementById('lblMessage');
                if (Username.length > 0) {
                    Cbo.DoCallBack('tbUsername', '');
                }
                else {
                    Cbo.AbortCallBack();
                    msg.innerHTML = '';
                }
            }

            function Cbo_Complete(responseText, responseXML) {
                var msg = document.getElementById('lblMessage');
                if (responseText == '0') {
                    msg.innerHTML = '用户名存在!';
                    msg.style.color = 'red';
                }
                else if (responseText == '1') {
                    msg.innerHTML = '用户名长度必须在3到15之间,且不包含字母、数字和下划线以外的字符!';
                    msg.style.color = 'red';
                }
                else if (responseText == "2") {
                    msg.innerHTML = '用户名不存在!';
                    msg.style.color = 'green';
                }
                else {
                    msg.innerHTML = '执行出现错误!';
                    msg.style.color = 'red';
                }
            }

            function Cbo_Error(status, statusText, responseText) {
                alert(responseText);
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:Label id="Label2" runat="server" Font-Names="黑体,Arial Black" Font-Bold="True" Font-Size="X-Large">基于AJAX的数据验证</asp:Label>
       <hr>
       <asp:Label id="Label1" runat="server">用户名:</asp:Label>
       <asp:TextBox id="tbUsername" runat="server" onkeyup="CheckUsername(this.value)" ontextchanged="tbUsername_TextChanged"></asp:TextBox>
       <br>
       <asp:Label id="lblMessage" runat="server"></asp:Label>
       <br>
       <%--<asp:TextBox ID="TextBox1" runat="server"
            AutoPostBack="True" ontextchanged="TextBox1_TextChanged"></asp:TextBox>--%>
        </form>
    </body>
    </html>
    与此页面对应的cs文件:

    protected void Page_Load(object sender, EventArgs e)
            {

            }

            protected void tbUsername_TextChanged(object sender, EventArgs e)
            {
                if (!CallBackHelper.IsCallBack)
                    return;

                string strName = tbUsername.Text;

                try
                {
                    string strReturnCode;
                    if (!IsValidUsername(strName))
                    {
                        strReturnCode = "1";
                    }
                    else if (!IsUsernameExist(strName))
                    {
                        strReturnCode = "2";
                    }
                    else
                    {
                        strReturnCode = "0";
                    }
                    CallBackHelper.Write(strReturnCode);
                }
                catch (Exception ex)
                {
                    CallBackHelper.HandleError(ex);
                }  
            }

            private bool IsUsernameExist(string strUsername)
            {
                bool bRet = false;

                switch (strUsername.ToLower())
                {
                    case "test":
                    case "tom":
                    case "jack":
                    case "ajax":
                    case "aspnet":
                        bRet = true;
                        break;
                }

                return bRet;
            }

            private bool IsValidUsername(string strUsername)
            {
                return (Regex.IsMatch(strUsername, @"^(\w{3,15})$"));
            }

            protected void TextBox1_TextChanged(object sender, EventArgs e)
            {
                Response.Redirect("http://www.g.cn");
            }

    2009年5月26日 12:15

答案

  • AutoPostBack 只是表示 TextBox 控件失去焦点时是否发生自动回发到服务器的操作,与是否有文字内容变化无关。你的事件是ontextchanged,所以,只要文字有变化,就会触发。

    【孟子E章】
    2009年5月26日 12:47
    版主

全部回复

  • AutoPostBack 只是表示 TextBox 控件失去焦点时是否发生自动回发到服务器的操作,与是否有文字内容变化无关。你的事件是ontextchanged,所以,只要文字有变化,就会触发。

    【孟子E章】
    2009年5月26日 12:47
    版主
  • 如果我不使用XMLHttp的话,在一个什么都没有的ASP.NET上托一个TextBox,双击它在TextBox1_TextChanged()函数里添加代码。
    运行后改变TextBox里的值,并没有反应。是不是这时候它不执行TextBox1_TextChanged里代码,只有设置为AutoPostBack才执行
    TextBox1_TextChanged里的代码?
    做最好的自己
    2009年5月27日 7:16
  • NineTyNine_LiPei:

    可以展示你的具体代码吗?谢谢!


    For Account Validation, please follow "Verify Account+Number" at http://social.msdn.microsoft.com/Forums/en-us/home?forum=reportabug

    For ASP.NET Question, please ask at http://forums.asp.net

    For other questions, you can find a specific forum and then ask at http://stackexchange.com/sites

    Click and Donate at http://www.freerice.com

    2013年11月10日 9:15