Monday, December 19, 2011

Cookies in asp.net

Client Side State Mangements
(QueryString,Cookies,Control State,Hidden Field,ViewState)

For QueryString:  Click to View Example

For ViewState:     Click to View Example

For Hidden Field :  Click to View Example

For Control State:   Click to View Example
Cookies:



A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.







You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.





Example


in .aspx page


<form id="form1" runat="server">
    <div>
        <h2 style="color:Teal">asp.net Cookie example: Create a cookie</h2>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="SeaGreen">
        </asp:Label>
        <asp:Label ID="Label2" runat="server" Font-Size="Large" ForeColor="Crimson">
        </asp:Label>
    </div>
    </form>

in .cs page

using System;
using System.Data;
using System.Web;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
        HttpCookie userCookie = new HttpCookie("UserInfo");
        userCookie["Country"] = "Italy";
        userCookie["City"] = "Rome";
        userCookie["Name"] = "Jones";
        userCookie.Expires = DateTime.Now.AddDays(3);
        Response.Cookies.Add(userCookie);
        Label1.Text = "Cookie create successful!<br><br/>";
        
        HttpCookie cookie = Request.Cookies["UserInfo"];
        
        if (cookie != null) 
        {
            string country = cookie["Country"];
            string city = cookie["City"];
            string name = cookie["Name"];
            Label2.Text = "Cookie Found and read<br/>";
            Label2.Text += "Name: " + name;
            Label2.Text += "<br />Country: " + country;
            Label2.Text += "<br />City: " + city;
        }
    }
}
















No comments:

Post a Comment