What is Cookies in Asp.Net [Demo]

Leave a Comment

A Cookies is a small piece of text stored on user's computer. Usually, information is stored as name-value pails. Cookies are used by websites to keep track of visitors. Every time a user visits a websie, cookise are retrieved from user machine and help identify the user.

A cookie is defined in the http header. use the HttpResponse class to send a cookie to the client. Response is a property of the page class that returns an object of type HttpResponse. The HttpResponse class defines the Cookies property that returns an HttpcookieCollection. Multiple cookies can be returned to the client with the HttpCookiecollection.

For example, if a user requests a page from your site and your application sends not just a page, but also a cookie containing the date and time, when the user's browser also gets the page, the browser also gets the cookie, which it stores in a folder on the user's hard disk.

You can add cookies to the cookies collection in a number of ways. The  following example shows two methods to write cookies:
Response.cookies["userName"].Value = "ajay";
Response.cookies["userName"].Expires = DateTime.Now.AddDAYS(1);
HttpCookie aCookie = new HttpCookie("lastvisit");                                                                   aCookie.Value = DateTime.Now.Tostring( );                                                                                                         aCookie.Expires = DateTime.Now.AddDays(1);                                                                                     Response.cookies.Add(aCookies);

Cookies are used for many purposes, all relating to helping the Web site remember users. For example, a site conducting a poll migut use a cookie simply as a Boolean value to indicate whether a user's browser has already participated in voting so that the user cannot vote twice. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials.
Let's see an example which makes use of Cookies to customize web page.
if(Reguest.Cookies["userId"]!=null)
{                                                                                                                                                                                   lbMessage.text = "Daer" + Request.Cookies["userId"].Value + ", Welcome to our website!";
}
else
{
lbMessage.text = "Guest, Welcome to our website!";
}

If you want to store client's information use the below code
Response.Cookies["userId"].value=username;

Examples:

Default.aspx
<body runat="server" id="BodyTag">
    <form id="form1" runat="server">
    <asp:DropDownList ID="ColorSelector" AutoPostBack="true" runat="server"
        onselectedindexchanged="ColorSelector_SelectedIndexChanged">
        <asp:ListItem Selected="True">White</asp:ListItem>
        <asp:ListItem>Red</asp:ListItem>
        <asp:ListItem>Green</asp:ListItem>
        <asp:ListItem>Blue</asp:ListItem>
    </asp:DropDownList>
    </form>
</body>
Default.aspx.cs
 protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["BackgroundColor"] != null)
        {
            ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;
            BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        }
    }
    protected void ColorSelector_SelectedIndexChanged(object sender, EventArgs e)
    {
        BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        HttpCookie cookie = new HttpCookie("BackgroundColor");
        cookie.Value = ColorSelector.SelectedValue;
        cookie.Expires = DateTime.Now.AddMinutes(1);
    }
Demo
Cookie Demo

Download Complete Source Code

0 comments:

Post a Comment