Cookies in ASP.NET using VB.NET

In this article we will learn how to create cookies in ASP.NET.
  • 3684

In this article you will learn how to create cookies in ASP.NET.

Cookies

Some information managed on client side and can be read when a website is navigate OR Cookie are one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.

Request object is used to read the data on client using Cookies collection.

Response object's Cookies collection is used to send the cookie to the client.

Use HttpCookie class to create the cookies.

Cookies can be of two types.

  1. Temporary Cookie (default)

  2. Permanent Cookie

To make a cookie as permanent cookie use Expires property of a cookie

Example:

Create a web form having two buttons.

  1.  Create Cookie

  2.  Show Cookie

When Create Cookies is click then manage a cookie as lv to manage the last visit.

Form looks like this.

cokies3.gif
 

Figure 1.

Creating the Cookie: To create cookies add the following code with create cookie button.

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

        Dim c As New HttpCookie("lv")

        c.Value = DateTime.Now.ToString()

        c.Expires = DateTime.Now.AddMonths(2)

        Response.Cookies.Add(c)

    End Sub

Reading the value of cookie: To Reading the value of cookie add the following code with show cookie button.

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click

        If Request.Cookies("lv") IsNot Nothing Then

            Response.Write(Request.Cookies("lv").Value)

        Else

            Response.Write("Cookie not found")

        End If

    End Sub

Now save and run the application.

Now we click on the button create cookies cookies will be created. and to show the value of cookies click on the button show cookies.

cokies 4.gif
 

Figure 2.

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.