Apr 18, 2011

Session state -- Cookies

Cut and paste the code as Shown

default.aspx
<%--<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>--%>


default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {

        //how to check browser supports cookies
        if (Request.Browser.Cookies)
        {
            Response.Write("Browser supports cookies");
        }
        else
        {
            // Web browser not supports cookies
        }


        string MyCookieValue="hello";
        // We need to perform this check first, to avoid null exception
        // if cookie not exists
        if (Request.Cookies["MyCookieName"] != null)
            MyCookieValue = Request.Cookies["MyCookieName"].Value;
        Label1.Text = MyCookieValue;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // Use this line when you want to save a cookie
        Response.Cookies["MyCookieName"].Value = TextBox1.Text ;
        // How long will cookie exist on client hard disk
        Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);

        // To add multiple key/value pairs in single cookie
        Response.Cookies["VisitorData"]["FirstName"] = "Richard";
        Response.Cookies["VisitorData"]["LastVisit"] = DateTime.Now.ToString();

    }
//  HttpCookie MyGreatCookie = new HttpCookie("MyCookieName");
//  MyGreatCookie.Value = "Some cookie value";
//  MyGreatCookie.Expires = DateTime.Now.AddDays(100);
//  Response.Cookies.Add(MyGreatCookie);


//    Cookie size is limited to 4096 bytes. It is not much, so cookies are used to store
//    small amounts of data, often just user id.

//    Also, number of cookies is limited to 20 per website.
//    If you make new cookie when you already have 20 cookies, browser will delete oldest one.

No comments:

Image Gallery - Image Add/Delete/Preview - Single Page App -

https://github.com/TheKalin/jQuery-File-Upload.MVC5 Helper Class / Models   public class FilesHelperDB     {         dbImageGallery...