Most of us may not know how to use/customize the Login control given by Visual Studio. For all my previous development experience, I always develop my own login form because I felt that it is much more customizable, and function can just be added in easily, such as "Remember Me".
In order to build "Remember Me" manually without using the Login control, guess you know that you need to have the login form ready as below:
- Username (textbox)
- Password (textbox, password)
- Login (button)
- Remember Me (checkbox)
Then, you need to have the following chunks of code to be placed in the respective section in the code behind, or I usually call it as VB.Net.
Code in PageLoad( )
If
Not Request.Cookies("anyname") Is Nothing Then
If Not Request.Cookies("anyname")("username") Is Nothing Then
Me.txtUsername.Text = Request.Cookies("anyname")("username")
End If
End If
This is to display the username in the "Username" textbox if it was "remembered"
Code in Login button
If
Me.chkRemember.Checked Then
Dim cookie As HttpCookie = New HttpCookie("anyname")
cookie.Values("username") = Me.txtUsername.Text
cookie.Expires = DateTime.Now.AddDays(14)
Response.Cookies.Add(cookie)
End If
This is to "remember" the username when the login button is click AND the "Remember Me" checkbox is checked. The duration is set as 14 days.
Optional Code in Logout button
If Not Request.Cookies("anyname") Is Nothing Then
Dim cookie As HttpCookie = Request.Cookies("anyname")
cookie.Expires = DateTime.Now.AddDays(-1)
Response.Cookies.Add(cookie)
End If
This is the optional code when the user perform a logout. You may put this code in a Link Button with caption as "Delete Cookies" to allow the user to remove the remembered username so that it won't be display in the "Username" textbox on the next login.
There you go. Simple and nice. If you would like to "remember" password as well, just add another cookie values as "password" with the assigned value.
No comments:
Post a Comment