aspnet
  1. aspnet-cookie

Cookie - (ASP.NET Web Forms)

When you want to store user-specific data on the client-side, cookies come in handy. In ASP.NET Web Forms, you can use the cookie mechanism to achieve this purpose. In this page, we will discuss how to create, read, and manipulate cookies in ASP.NET Web Forms.

Syntax

A cookie can be created in ASP.NET using the HttpCookie class. Here's the syntax to create a cookie:

Response.Cookies["myCookie"].Value = "cookie value";

To retrieve a cookie's value, you can use the following syntax:

string cookieValue = Request.Cookies["myCookie"].Value;

Example

Here's an example that demonstrates the use of cookies in ASP.NET Web Forms.

protected void Page_Load(object sender, EventArgs e)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie["FontSize"] = "Large";
    myCookie.Expires = DateTime.Now.AddDays(1d);
    Response.Cookies.Add(myCookie);
}

protected void btnReadCookie_Click(object sender, EventArgs e)
{
    HttpCookie myCookie = Request.Cookies["UserSettings"];
    if (myCookie != null)
    {
        string fontSize = myCookie["FontSize"];
        lblFontSize.Text = "Font size: " + fontSize;
    }
}

In the Page_Load event, we create a cookie named "UserSettings" and add its value as "Large". We also set it to expire in one day.

In the btnReadCookie_Click event, we retrieve the "UserSettings" cookie's value and extract the FontSize value from it. We then display that value on a label control named lblFontSize.

Output

The output of the above example will display the font size ("Large") on the screen when the user clicks on the "Read Cookie" button.

Explanation

Cookies are small files stored on the client-side that keep track of session information and user data. They are used to maintain the session state of a Web application.

The HttpCookie class represents an individual cookie in ASP.NET. The syntax for creating a cookie is Response.Cookies["CookieName"].Value = "CookieValue";.

The syntax for retrieving a cookie value is string cookieValue = Request.Cookies["CookieName"].Value;.

Use

In ASP.NET Web Forms, cookies can be used to customize the user experience or store user-specific settings. By using cookies, you can store a small amount of data on the client-side that persists across different page requests.

Important Points

  • Cookies are used to store session information and user data on the client-side.
  • To create a cookie, use the HttpCookie class, and add it to the Response.Cookies collection.
  • To retrieve a cookie value, use the Request.Cookies collection.

Summary

In this page, we discussed how to create, read, and manipulate cookies in ASP.NET Web Forms. We covered the syntax, example, output, explanation, use, important points, and summary of cookies in ASP.NET Web Forms. By using cookies in ASP.NET Web Forms, you can store user-specific data and provide custom experiences tailored to individual users.

Published on: