简体   繁体   English

按钮单击时从母版页中删除元素

[英]remove element from master page on button click

So here is the deal I am working on a simple project, with a log in form and a sign up form. 所以这是我正在处理一个简单项目的交易,具有登录表单和注册表单。 In the beginning you will see this which is displayed in the picture. 在开始时,您将看到图片中显示的内容。

在此输入图像描述

After you sign up or log in, then you will get what is displayed in the picture below 注册或登录后,您将看到下图中显示的内容

在此输入图像描述

When I click on a new page for example: like on the home page, videos, contact, then it will just return back to its original state in the first picture. 当我点击一个新页面时,例如:在主页上,视频,联系人,然后它将返回到第一张图片中的原始状态。 I want to prevent that and keep it the way it is in the second picture until you click on log out. 我希望防止这种情况,并在第二张照片中保持原样,直到您点击退出为止。 I have been looking everywhere for answers and can't seem to find exactly what I am looking for. 我一直在寻找答案,似乎无法找到我正在寻找的东西。

Here is a little code from what I have used to try and accomplish this 以下是我用来尝试完成此操作的一些代码

HTML code, which is located in the master page HTML代码,位于母版页中

<a id ="LogIn" runat="server" href="../LogIn.aspx">Log In:</a>
<a id ="SignUp" runat="server" href="../SignUp.aspx">Sign Up:</a>
<a id ="LogOut" href="../LogIn.aspx">Log Out:</a> 

CSS code in the master page as well. 主页面中的CSS代码也是如此。

#LogIn
{
    margin-top: 10px;
    font-size: 25px;
    position: absolute;
    margin-left: 767px;
}
#SignUp
{
    margin-top: 10px;
    font-size: 25px;
    position: absolute;
    margin-left: 867px;
}
#LogOut
{
    margin-top: 30px;
    font-size: 20px;
    position: absolute;
    margin-left: 880px;
    display: none;
}

Okay I have tried doing it in javascript, which is in the master page 好吧,我已经尝试在javascript中进行,这是在母版页中

    function showAlert() {
        $(".SignUp").slideUp("25000");
        $(".LogIn").slideUp("25000");
        $(".CreateAccount").hide();
        $(".AccountLogIn").hide();
        $("h1").remove();
        $("#LogIn").remove();
        $("#SignUp").remove();
        $("#LogOut").show();
    }

the showalert function is being called from the button click event in C# for the LogIn form and SignUp form 对于LogIn表单和SignUp表单,从C#中的按钮单击事件调用showalert函数

SqlConnection connection = new SqlConnection();

protected void Page_Load(object sender, EventArgs e)
{
    connection.ConnectionString = @"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=**************";
    connection.Open();
}

public void CheckEmail()
{
    SqlCommand Comm = new SqlCommand("select count(*) from SignUp where Email ='" + Email.Text + "'", connection);


    Comm.Parameters.AddWithValue("@Email", Email.Text);
    Comm.Connection = connection;
    int count = Convert.ToInt32(Comm.ExecuteScalar());


    if (count > 0)
    {
        Thread.Sleep(3000);
        VerifyEmail.Visible = true;
    }
    else
    {
        Thread.Sleep(5000);
        InsertData();

        VerifyEmail.Visible = false;
        Message.Visible = true;
        LogInAs.Visible = true;
        LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
        this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
    }
}

public void InsertData()
{

    SqlCommand Command = new SqlCommand("Insert into SignUp" + "(FirstName, LastName, Password, Email)values(@FirstName, @LastName, @Password, @Email)", connection);

    Command.Parameters.AddWithValue("@FirstName", FirstName.Text);
    Command.Parameters.AddWithValue("@LastName", LastName.Text);
    Command.Parameters.AddWithValue("@Password", Password.Text);
    Command.Parameters.AddWithValue("@Email", Email.Text);
    HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
    HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");

    LogIn.Visible = false;
    SignUp.Visible = false;

    Command.ExecuteNonQuery();

}

protected void SignUp_Click(object sender, EventArgs e)
{
    CheckEmail();

    connection.Close();

    //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showAlert", "showAlert()", true);
    //Response.Write("<script language=JavaScript> alert('You have Successfully created an Account'); </script>");
    //Response.Redirect("~//Default.aspx");
}

I also tried doing it in the back end code as well shown above. 我也尝试在后端代码中执行此操作,如上所示。 It also shows how the user is being loged in and saved in the database. 它还显示了用户如何进入并保存在数据库中。 That is being called in the button click event, when you click to create an account or click to log into an account. 当您单击以创建帐户或单击以登录帐户时,将在按钮单击事件中调用该按钮。

LogIn.aspx.cs LogIn.aspx.cs

SqlConnection conn = new SqlConnection();

protected void Page_Load(object sender, EventArgs e)
{
    conn.ConnectionString = @"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=*******";
    conn.Open();
}

private bool CompareStrings(string string1, string string2)
{
    return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}

public void ExecuteLogIn()
{

    SqlCommand Command = new SqlCommand("select ISNULL(Email, '') As Email, ISNULL(Password, '') As Password from SignUp where Email='" + Email.Text + "'",  conn);
    SqlCommand Command2 = new SqlCommand("select * from SignUp where FirstName= @FirstName", conn);

    Command2.Parameters.AddWithValue("@FirsName", FirstName.Text);

    SqlDataReader dr = Command.ExecuteReader();

    string UserEmail = Email.Text;
    string UserPassword = Password.Text;

    HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
    HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");

    while (dr.Read())
    {
        if (this.CompareStrings(dr["Email"].ToString(), UserEmail) &&
             this.CompareStrings(dr["Password"].ToString(), UserPassword))
        {
            InvalidLogIn.Visible = false;
            Message.Visible = true;
            LogInAs.Visible = true;
            //LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
            this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));

            LogIn.Visible = false;
            SignUp.Visible = false;
        }
        else
        {
            InvalidLogIn.Visible = true;
        }
    }


    //Command.Parameters.AddWithValue("@Password", Password.Text);
    //Command.Parameters.AddWithValue("@Email", Email.Text);

    conn.Close();
}

protected void LogIn_Click(object sender, EventArgs e)
{
    ExecuteLogIn();
}

Any help would be greatly appreciated thanks so much 非常感谢任何帮助,非常感谢

The code is missing too many pieces. 代码缺少太多部分。 I could only give you a direction. 我只能给你一个方向。 If you have specific question about FormAuthentication, please create a new question. 如果您对FormAuthentication有特定问题,请创建一个新问题。

  1. CheckEmail method is prone to SQL Injection attack . CheckEmail方法很容易受到SQL注入攻击 You want to consider using Parameterized Query. 您想要考虑使用参数化查询。

  2. We normally need both username*(or email)* and password to validate an account. 我们通常需要用户名*(或电子邮件)*和密码来验证帐户。 Easiest way to implement authentication in ASP.NET Web Form is to use FormAuthentication . ASP.NET Web窗体中实现身份验证的最简单方法是使用FormAuthentication

The following is the sample code. 以下是示例代码。 I also created a sample project at GitHub , so that you can test it. 我还在GitHub上创建了一个示例项目 ,以便您可以对其进行测试。

Sign-In method inside Login.aspx.cs Login.aspx.cs中的登录方法

protected void SubmitButton_Click(object sender, EventArgs e)
{
    string username = UsernameTextBox.Text,
        password = PasswordTextBox.Text;
    bool rememberMe = RememberMeCheckBox.Checked;

    // Retrieve username and hashed password from database, and validate them
    if (username.Equals("johndoe", StringComparison.InvariantCultureIgnoreCase) &&
        password.Equals("123456", StringComparison.InvariantCultureIgnoreCase))
    {
        FormsAuthentication.RedirectFromLoginPage(username, rememberMe);
    }
    MessageLabel.Text = "Invalid username or password";
}

Global.asax.cs 的Global.asax.cs

We then retrieve username from cookie, and save it in Principal Object. 然后,我们从cookie中检索用户名,并将其保存在Principal Object中。

public class Global : HttpApplication
{
    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (decryptedCookie != null)
        {
            FormsAuthenticationTicket ticket =
                FormsAuthentication.Decrypt(decryptedCookie.Value);

            var identity = new GenericIdentity(ticket.Name);
            var principal = new GenericPrincipal(identity, null);

            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal = HttpContext.Current.User;
        }
    }
}

web.config web.config中

Please ensure authentication tag is in web.config. 请确保身份验证标记位于web.config中。

<authentication mode="Forms">
   <forms loginUrl="~/Login.aspx" />
</authentication>

Usage 用法

protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        string username = User.Identity.Name;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM