按钮仅在第二次单击时起作用

时间:2015-01-06 07:59:37

标签: c# asp.net button

我正在尝试创建一个连接到数据库的ASP.NET基本站点。它应该允许用户注册和登录。

我用javascript和后面的代码检查输入,以防它被禁用。

问题在于,无论何时我第一次点击注册,登录或注销按钮,它们都将无效;页面保持不变。 然而,第二次,他们完美地工作。 调试器说这两次都被调用了。

任何想法?

ASP:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs" 
Inherits="Register_and_Login.Main" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript">
    function isUserValid() {
    var UserLength = document.getElementById("UserTB").value.length;
    var ValidatorLabel = document.getElementById("ValidateUser");
    if (UserLength < 6 || UserLength > 15) {
        ValidatorLabel.style.display = 'inline';
        return false;
        }
    else {
        ValidatorLabel.style.display = 'none';
        return true;
    }  
    }
    function isPassValid() {
        var PassLength = document.getElementById("PasswordTB").value.length;
        var ValidatorLabel = document.getElementById("ValidatePassword");
        if (PassLength < 6 || PassLength > 15) {
            ValidatorLabel.style.display = 'inline';
            return false;
        }
        else {
            ValidatorLabel.style.display = 'none';
            return true;
        } 
    }
    function isConfirmValid() {
        var Password = document.getElementById("PasswordTB").value;
        var Me = document.getElementById("ConfirmTB").value;
        var ValidatorLabel = document.getElementById("ValidateConfirm");
        if (Password == Me) {
            ValidatorLabel.style.display = 'none';
            return true;
        }
        else {
            ValidatorLabel.style.display = 'inline';
            return false;
        }
    }
    function isEmailValid() {
        var str = document.getElementById("EmailTB").value;
        var lastAtPos = str.lastIndexOf('@');
        var lastDotPos = str.lastIndexOf('.');
        var isFine = (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
        var ValidationLabel=document.getElementById("ValidateEmail");
        if(isFine)
        {
            ValidationLabel.style.display='none';
            return true;
        }
        else
        {
            ValidationLabel.style.display='inline';
            return false;
        }
    }
</script>
<title></title>
<style type="text/css">
    .Validators
    {
        display:none;
    }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:Panel id="RegisterRelated" runat="server">
    Username:<br />
    <asp:TextBox ID="UserTB" runat="server" OnChange="isUserValid()" AutoPostBack="false"></asp:TextBox>
    <asp:Label ID="ValidateUser" runat="server" ForeColor="Red" 
        Text="Username must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
    <br />
    Password:<br />
    <asp:TextBox ID="PasswordTB" runat="server" OnChange="isPassValid()" AutoPostBack="false"></asp:TextBox>
    <asp:Label ID="ValidatePassword" runat="server" ForeColor="Red" 
        Text="Password must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
    <br />
    Confirm password:<br />
    <asp:TextBox ID="ConfirmTB" runat="server" OnChange="isConfirmValid()" AutoPostBack="false"></asp:TextBox>
    <asp:Label ID="ValidateConfirm" runat="server" ForeColor="Red" 
        Text="This field must match the password field." CssClass="Validators"></asp:Label>
    <br />
    Email:<br />
    <asp:TextBox ID="EmailTB" runat="server" OnChange="isEmailValid()" AutoPostBack="false"></asp:TextBox>
    <asp:Label ID="ValidateEmail" runat="server" ForeColor="Red" Text="Invalid Email." CssClass="Validators"></asp:Label>
    <br />
    <br />
    <asp:Button ID="Register" runat="server" Text="Register" onclick="Register_Click" EnableViewState="false"/>
    <br />
    <asp:Panel ID="Answer" runat="server" >
    </asp:Panel>
    </asp:Panel>
    <br />
    <br />
    <asp:Panel id="LoginRelated" runat="server">
    User: 
    <asp:TextBox ID="LoginUserTB" runat="server" AutoPostBack="false"></asp:TextBox>
    <br />
    Password:
    <asp:TextBox ID="LoginPassTB" runat="server" AutoPostBack="false"></asp:TextBox>
        <br />
    <asp:Button ID="Login" runat="server" Text="Login" onclick="Login_Click" EnableViewState="false" />
    <br />
    </asp:Panel>
    <asp:Panel ID="InPage" runat="server">
    <asp:Panel ID="LogAnswer" runat="server">
    </asp:Panel>
    <br />
    <asp:Label ID="WelcomeTag" runat="server"></asp:Label>

        <br />
        <br />
        <asp:Button ID="logout" runat="server" onclick="logout_Click" Text="Logout" EnableViewState="false"/>

    </asp:Panel>
</div>
</form>
</body>
</html>

C#登录,退出&amp;注册按钮:

protected void Register_Click(object sender, EventArgs e)
    {
        Label Reply = new Label();
        if (Session["User"] == null)
        {
            Result myRegResult = Result.IN_PROG;
            User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
            DbManager.OpenDbConnection();
            myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
            Reply.Text = resultToString(myRegResult);
            Reply.ForeColor = resultColor(myRegResult);
        }
        else
        {
            Reply.Text = "You must log out before you register.";
            Reply.ForeColor = resultColor(Result.EXEC_ERROR);
        }
        Answer.Controls.Add((Control)Reply);
        //Reset_Fields();
    }


protected void Login_Click(object sender, EventArgs e)
    {
        Label Reply = new Label();
        LoginProc Status = LoginProc.IN_PROG;
        DbManager.OpenDbConnection();
        Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
        Reply.Text = ProcToString(Status);
        Reply.ForeColor = ProcToColor(Status);
        LogAnswer.Controls.Add(Reply);
        if (Status == LoginProc.FINE)
           Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
        //Reset_Fields();
    }



protected void logout_Click(object sender, EventArgs e)
    {
        Session["User"] = null;

    }

页面加载:

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["User"] != null)
        {
            RegisterRelated.Visible = false;
            LoginRelated.Visible = false;
            InPage.Visible = true;
            WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
        }
        else
        {
            RegisterRelated.Visible = true;
            LoginRelated.Visible = true;
            WelcomeTag.Text = String.Empty;
            InPage.Visible = false;
        }
    }
编辑:我的一位朋友建议我查看ASP.NET页面生命周期,它可能与页面显示后正在完成的数据库交互有关,如果有帮助的话。

4 个答案:

答案 0 :(得分:2)

您的朋友是正确的,您需要更好地了解Page Life周期的页面。基本上在这种情况下,您需要了解OnLoad事件发生在之前任何点击事件。您可以通过向OnLoad事件和单击处理程序添加断点来自行查看。你会看到发生事件的顺序。

在这个例子中,我会写一个方法来设置页面,然后在每个点击事件中调用它

private void setUpPage()
{
    if (Session["User"] != null)
    {
        RegisterRelated.Visible = false;
        LoginRelated.Visible = false;
        InPage.Visible = true;
        WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
    }
    else
    {
        RegisterRelated.Visible = true;
        LoginRelated.Visible = true;
        WelcomeTag.Text = String.Empty;
        InPage.Visible = false;
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    //Call if not in response to button click
    if(!IsPostBack)
    {
       setUpPage();
    }
}

protected void Register_Click(object sender, EventArgs e)
{
    Label Reply = new Label();
    if (Session["User"] == null)
    {
        Result myRegResult = Result.IN_PROG;
        User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
        DbManager.OpenDbConnection();
        myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
        Reply.Text = resultToString(myRegResult);
        Reply.ForeColor = resultColor(myRegResult);
    }
    else
    {
        Reply.Text = "You must log out before you register.";
        Reply.ForeColor = resultColor(Result.EXEC_ERROR);
    }
    Answer.Controls.Add((Control)Reply);
    //Reset_Fields();

    //Reset the fields as required AFTER you have done what you need with the database
    setUpPage();
}


protected void Login_Click(object sender, EventArgs e)
{
    Label Reply = new Label();
    LoginProc Status = LoginProc.IN_PROG;
    DbManager.OpenDbConnection();
    Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
    Reply.Text = ProcToString(Status);
    Reply.ForeColor = ProcToColor(Status);
    LogAnswer.Controls.Add(Reply);
    if (Status == LoginProc.FINE)
       Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
    //Reset_Fields();
    //Reset the fields as required AFTER you have done what you need with the database
    setUpPage();
}



protected void logout_Click(object sender, EventArgs e)
{
    Session["User"] = null;
    //Reset the fields as required AFTER you have done what you need with the database
    setUpPage();
}

答案 1 :(得分:1)

单击登录或注册按钮时,页面加载事件首先起作用, 按钮后单击事件起作用。

我可以看到,您在页面加载事件中设置为页面显示,并在按钮单击事件中设置为会话值。所以首先点击,首先触发页面加载事件,但是还没有会话值。页面加载事件使用按钮单击事件完成并恢复,因此会话值现在不为空(如果输入的用户信息有效)。 这就是为什么页面工作在第二次点击。

<强>解决方案:

protected void Page_Load(object sender, EventArgs e)
    {
        if (this.IsPostBack) //just write this
                return;

        if (Session["User"] != null)
        {
            RegisterRelated.Visible = false;
            LoginRelated.Visible = false;
            InPage.Visible = true;
            WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
        }
        else
        {
            RegisterRelated.Visible = true;
            LoginRelated.Visible = true;
            WelcomeTag.Text = String.Empty;
            InPage.Visible = false;
        }
    }

注意:我收到了您的代码并尝试过。

另见:http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx

答案 2 :(得分:0)

我认为验证器存在问题。请根据您的要求设置按钮的原因验证属性。

答案 3 :(得分:0)

在每Page_BlockSubmit = false;

之前尝试return false;