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

本文关键字:起作用 单击 第二次 按钮 | 更新日期: 2023-09-27 18:36:27

我正在尝试创建一个连接到数据库的 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# 登录、注销和注册按钮:

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 页面生命周期,如果它对任何人有帮助,它可能与页面呈现后完成的数据库交互有关。

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

你的朋友是对的,你需要更好地了解页面的页面生命周期。基本上在这种情况下,您需要了解 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();
}

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

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

溶液:

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

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

在每次return false;之前尝试Page_BlockSubmit = false;