TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

ASP.Net Cookie

ASP.Net Cookie with asp.net tutorial, asp.net introduction, features, project, example, server controls, labels, textbox, button, hyperlink, radiobutton, calender, checkbox, fileupload, events handling, authentication, webforms model binding, html server control, compare validdator, range validator, validation summary, mvc introduction, mvc project, view, validation, entity framework, authentication etc.

<< Back to ASP

ASP.NET Cookie

ASP.NET Cookie is a small bit of text that is used to store user-specific information. This information can be read by the web application whenever user visits the site.

When a user requests for a web page, web server sends not just a page, but also a cookie containing the date and time. This cookie stores in a folder on the user's hard disk.

When the user requests for the web page again, browser looks on the hard drive for the cookie associated with the web page. Browser stores separate cookie for each different sites user visited.

Note: The Cookie is limited to small size and can be used to store only 4 KB (4096 Bytes) text.

There are two ways to store cookies in ASP.NET application.

  • Cookies collection
  • HttpCookie

We can add Cookie either to Cookies collection or by creating instance of HttpCookie class. both work same except that HttpCookie require Cookie name as part of the constructor.


HttpCookie Example

In the following example, we are creating and adding cookie with the help of HttpCookie class.

// CookieExample.aspx

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="CookieExample.aspx.cs" Inherits="CoockieExample.CookieExample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
</html>

Code

// CookieExample.aspx.cs

using System;
using System.Web;
namespace WebFormsControlls
{
    public partial class CookieExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //-------------- Creating Cookie --------------------------//
            // Creating HttpCookie instance by specifying name "student"
                HttpCookie cokie = new HttpCookie("student");
            // Assigning value to the created cookie
                cokie.Value = "Rahul Kumar";
            // Adding Cookie to the response instance
                Response.Cookies.Add(cokie);
            //--------------- Fetching Cookie -------------------------//
            var co_val  = Response.Cookies["student"].Value;
            Label1.Text = co_val;
        }
    }
}

Cookie Collection Example

In the following example, we are adding cookie directly to the Cookies collection.

// Default.aspx

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="CoockieExample._Default" %>
<form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="Select Brand Preferences"></asp:Label>
    <br />
    <br />
    <asp:CheckBox ID="apple" runat="server" Text="Apple" />
    <br />
    <asp:CheckBox ID="dell" runat="server" Text="Dell" />
    <br />
    <asp:CheckBox ID="lenevo" runat="server" Text="Lenevo" />
    <br />
    <asp:CheckBox ID="acer" runat="server" Text="Acer" />
    <br />
    <asp:CheckBox ID="sony" runat="server" Text="Sony" />
    <br />
    <asp:CheckBox ID="wipro" runat="server" Text="Wipro" />
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
    <p>
        <asp:Label ID="Label2" runat="server"></asp:Label>
    </p>
</form>

CodeBehind

// Default.aspx.cs

using System;
using System.Web.UI;
namespace CoockieExample
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Setting expiring date and time of the cookies
            Response.Cookies["computer"].Expires = DateTime.Now.AddDays(-1);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label2.Text = "";
            // --------------- Adding Coockies ---------------------//
            if (apple.Checked)
                Response.Cookies["computer"]["apple"]  = "apple";
            if (dell.Checked)
                Response.Cookies["computer"]["dell"]   = "dell";
            if (lenevo.Checked)
                Response.Cookies["computer"]["lenevo"] = "lenevo";
            if (acer.Checked)
                Response.Cookies["computer"]["acer"]   = "acer";
            if (sony.Checked)
                Response.Cookies["computer"]["sony"]   = "sony";
            if (wipro.Checked)
                Response.Cookies["computer"]["wipro"]  = "wipro";
            // --------------- Fetching Cookies -----------------------//
            if (Request.Cookies["computer"].Values.ToString() != null)
            {
                if (Request.Cookies["computer"]["apple"] != null)
                    Label2.Text += Request.Cookies["computer"]["apple"] + " ";
                if (Request.Cookies["computer"]["dell"] != null)
                    Label2.Text += Request.Cookies["computer"]["dell"] + " ";
                if (Request.Cookies["computer"]["lenevo"] != null)
                    Label2.Text += Request.Cookies["computer"]["lenevo"] + " ";
                if (Request.Cookies["computer"]["acer"] != null)
                    Label2.Text += Request.Cookies["computer"]["acer"] + " ";
                if (Request.Cookies["computer"]["sony"] != null)
                    Label2.Text += Request.Cookies["computer"]["sony"] + " ";
                if (Request.Cookies["computer"]["wipro"] != null)
                    Label2.Text += Request.Cookies["computer"]["wipro"] + " ";
            }else Label2.Text = "Please select your choice";
            Response.Cookies["computer"].Expires = DateTime.Now.AddDays(-1);
        }
    }
}

Output:

This example will store selected values as cookie.

ASP Net Cookie 1
ASP Net Cookie 2
Next TopicASP.NET Session




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf