In this example, we will have two ASPX pages: One to write a cookie, and one to read this same cookie. The first ASPX page will look something like this:
<form id="form1" runat="server"> Cookie Name <asp:textbox id="NameField" runat="server"/><br /> Cookie Value <asp:textbox id="ValueField" runat="server"/><br /> <asp:button ID="Button1" text="WriteCookie" onclick="WriteClicked" runat="server" /><br /> <asp:HyperLink ID="lnkRead" NavigateUrl="Read.aspx" runat="server" Visible="false">Read the cookies <br /> </form>
code behind
Partial Public Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub WriteClicked(ByVal Sender As Object, ByVal e As EventArgs) Handles Button1.Click lnkRead.Visible = True lnkRead.NavigateUrl = "Read.aspx?cookie=" & NameField.Text.ToString()
'Create a new cookie, passing the name into the constructor Dim cookie As New HttpCookie(NameField.Text)
'Set the cookies value cookie.Value = ValueField.Text
'Set the cookie to expire in 1 minute Dim dtNow As DateTime = DateTime.Now Dim tsMinute As New TimeSpan(0, 0, 1, 0) cookie.Expires = dtNow.Add(tsMinute)
'Add the cookie Response.Cookies.Add(cookie)
lblRead.Text = "Cookie written." End Sub End Class
Now create a page to read the cookie ::
<form id="form1" runat="server"> <asp:Label ID="lblCookie" runat="server"></asp:Label> </form>
code behind
Partial Class Read Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Request.QueryString("cookie") IsNot Nothing Then ReadCookie() End If End Sub
Protected Sub ReadCookie() 'Get the cookie name the user entered Dim strCookieName As String = Request.QueryString("cookie").ToString()
'Grab the cookie Dim cookie As HttpCookie = Request.Cookies(strCookieName)
'Check to make sure the cookie exists If cookie Is Nothing Then lblCookie.Text = "Cookie not found.
" Else 'Write the cookie value Dim strCookieValue As String = cookie.Value.ToString() lblCookie.Text = "The " & strCookieName & " cookie contains: " & strCookieValue & "
" End If End Sub End Class
|
No responses found. Be the first to respond and make money from revenue sharing program.
|