javascript - 单击按钮时从主页中删除元素

标签 javascript c# html asp.net

这是我正在做的一个简单项目的交易,有一个登录表单和一个注册表单。一开始您会看到图片中显示的内容。

enter image description here

注册或登录后,您将看到下图所示的内容

enter image description here

当我点击一个新页面时,例如:主页、视频、联系人,那么它就会返回到第一张图片中的原始状态。我想防止这种情况发生,并保持第二张图片中的样子,直到您单击注销。我一直在到处寻找答案,但似乎找不到我想要的东西。

这是我用来尝试完成此任务的一些代码

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 代码。

#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;
}

好吧,我已经尝试用 javascript 来完成它,它位于母版页中

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

从 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");
}

我也尝试在后端代码中执行此操作,如上所示。它还显示用户如何登录并保存在数据库中。当您单击创建帐户或单击登录帐户时,将在按钮单击事件中调用该函数。

登录.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();
}

任何帮助将不胜感激,非常感谢

最佳答案

代码缺少太多部分。我只能给你一个方向。如果您对 FormAuthentication 有具体问题,请创建一个新问题。

  1. CheckEmail 方法容易出现 SQL Injection attack 。您要考虑使用参数化查询。

  2. 我们通常需要用户名*(或电子邮件)*和密码来验证帐户。在 ASP.NET Web 表单 中实现身份验证的最简单方法是使用 FormAuthentication

下面是示例代码。我还创建了 a sample project at GitHub ,以便您可以测试它。

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

然后我们从 cookie 中检索用户名,并将其保存在主体对象中。

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 中。

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

用法

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

关于javascript - 单击按钮时从主页中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43300153/

相关文章:

javascript - 如何在 jQuery 中通过 .post 发送数组?

javascript - 更改触摸 :TouchList is not a property?

javascript - 如何复制 HTML 和用户输入,然后通过 HTTP 请求将其发送到服务器?

C# mysql插入查询,如果记录存在则更新

c# - 对象创建,如何解析 "class-owner"?

html - Twitter Bootstrap 导航列表中的长文本跨越容器边界

html - 我如何在一条直线上获得这些图片?

javascript - Nativescript 无限翻译动画

c# - 从字符串生成子字符串的组合

html - CSS 动画不显示所有内容