Practical of Cookies


In this Article we creates cookies and use these cookies on the another page .In the previous Article we discuss about the concept of cookies. If you understand all the theoritical concept related Cookies now we do some practilce for better understanding.

Practicle Implementation of the Cookies

I guess you all are familiar with Visual Studio ( VS).

Step 1. Select webform from the VS. Now Place Two Text Box and one button from the Toolbox.


Cookies Sample Image1

Step 2. Now Press on the Botton and its event is fire Now place this place under the button's Event.


protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "abc" && TextBox2.Text == "xyz")
{
HttpCookie ck = new HttpCookie("myckk"); // Class is use to create the Cookies

ck.Values.Add("un", TextBox1.Text); // Add the subkey to the Cookies class object i.e ck which we define in the above line
ck.Values.Add("up", TextBox2.Text);

ck.Expires = DateTime.Now.AddHours(1); // Define the time interval to expire the cookies
//ck.Expires = DateTime.Now.Add(new TimeSpan(20, 30, 20));

Response.Cookies.Add(ck);
Response.Redirect("Default2.aspx");
}
else
{
Response.Write("Wrong UserName/Password");
}
}


Note : Use abc and xyz in the Textbox1 and Textbox2 . If both the values are correct then these values are added in the object i.e ck. And we can access and check the values of these subkeys.



Step 3. Similarly add the new page under the same Solution. Place two Textboxes, a Label and a Button .

Cookies Sample Image2

Now we Check Cookies are created or not , To check the cookies are created or not double click on the
button and use the below code.On page load we request and check whether cookies are created or not if cookies are created then it shows the Welcome message with Name otherwise it move to else part and display the message i.e Cookies are not Created.

protected void Page_Load(object sender, EventArgs e)
{
HttpCookie k = Request.Cookies["myckk"];
if (k != null)
{
Label1.Text = "Welcome : " + k.Values["un"].ToString();
}
else
{
Response.Write("Cookies not Created");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie kk = Request.Cookies["myckk"];
if (kk != null)
{
if (TextBox1.Text == kk.Values["un"] && TextBox2.Text == kk.Values["up"])
{
Label1.Text = "Login";
}
else
{
Label1.Text = "Not Login";
}
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: