Cookies in ASP.Net Example


Cookies is a small piece of information stored on the client machine.It is used to store user preference information like Username, Password,City and Phone Number etc on client machines. We need to import namespace called  System.Web.HttpCookie before we use cookie. 
  
Type of Cookies?

Persist Cookie - A cookie has not have expired time Which is called as Persist Cookie.

Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie.



1) Open a new ASP.NET Empty Web Application.



2) Right Click on Project.
Add > New Item > Web Form



3) Now Create sample form using design.



4) Double Click on Button and add following code . 

protected void Button1_Click(object sender, EventArgs e)
        {
            HttpCookie form = new HttpCookie("form");
            Response.Cookies["form"]["fname"] = fnamebox.Text;
            Response.Cookies["form"]["lname"] = lnamebox.Text; 

            Response.Redirect("Response.aspx");
        }

5) Create another page named "response.aspx".
Add a Label in it named Label1.





6) Add Following code to 'Response.aspx.cs"


protected void Page_Load(object sender, EventArgs e)
        {
            string name = " " + Request.Cookies["form"]["fname"] + " " + Request.Cookies["form"]["lname"] ;
            Label1.Text = name; 
        }

In this demo we are creating cookies in one page and retrieving it in another page.


Advantages of Cookie:


  • Its clear text so user can able to read it.
  • We can store user preference information on the client machine.
  • Its easy way to maintain.
  • Fast accessing.


Disadvantages of Cookie:


  • If user clear cookie information we can't get it back.
  • No security.
  • Each request will have cookie information with page.






   

0 comments:

Related Posts Plugin for WordPress, Blogger...
Copyright © 2013 futureX | Blogger Template by Clairvo