Monday, 16 March 2015

Implement Remember Me functionality using CheckBox in ASP.Net C#

HTML Markup
I have a simple HTML Form below which has two ASP.Net TextBox controls txt_UserName  and  txt_Password and a CheckBox control chk_RememberMe to allow user specify whether he wants the page to remember the UserName and Password when he visits next time, finally an ASP.Net Button  btn_Login which when clicked will save the entered UserName and Password in the Cookie.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    UserName:
    <asp:TextBox ID="txt_UserName" runat="server"></asp:TextBox><br />
    Password:
    <asp:TextBox ID="txt_Password" TextMode="Password" runat="server"></asp:TextBox><br />
    Remember me:
    <asp:CheckBox ID="chk_RememberMe" runat="server" /><br />
    <asp:Button ID="btn_Login" runat="server" Text="Login" OnClick="btn_Login_Click" />
    </form>
</body>
</html>
Saving the UserName and Password in Cookie
When the Button btn_Login is clicked the following event handler is executed which first checks whether the chk_RememberMe is checked. If it is checked then it save the UserName and Password in the Cookies and sets their expiration date to 30 days in future from the current date. And if it is not checked then it sets the expiration date to 1 day in past so that Cookie is destroyed.
C#
protected void btn_Login_Click(object sender, EventArgs e)
{
    if (chk_RememberMe.Checked)
    {
        Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30);
        Response.Cookies["Password"].Expires = DateTime.Now.AddDays(30);
    }
    else
    {
        Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
        Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);
 
    }
    Response.Cookies["UserName"].Value = txt_UserName.Text.Trim();
    Response.Cookies["Password"].Value = txt_Password.Text.Trim();
}
 Populating the UserName and Password from Cookie and setting it in TextBoxes
Now in Page_Load event we will check if the Cookie exists and if yes then we will set the TextBoxes for UserName and Password with their respective Cookie value.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
      if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
        {
         txt_UserName.Text = Request.Cookies["UserName"].Value;
         txt_Password.Attributes["value"] = Request.Cookies["Password"].Value;
        }
    }
}

No comments:

Post a Comment