How to Create cookies in asp.Net
In this post I am going to show you how you can create a cookie in Microsoft ASP.net and use that cookie. Cookies are actually data send by the website and saved in your web browser during browsing a website.When the user visits the same website again, the information stored in the cookie is sent back to the website by the browser to give the website of the user's earlier activities and other details.
In this post I am going to show you how you can create a cookie in Microsoft ASP.net and use that cookie.
First of all create new project and place a label, one text box and one button on the web page.Now, open the aspx.cs of your webpage to view its source code and write the following code in that page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
Label1.Text = "New user ...!!!
";
}
else
{
Label1.Text = "Cookie has been found...
";
Label1.Text += "Welcome, " + cookie["Name"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
cookie = new HttpCookie("Preferences");
}
cookie["Name"] = TextBox1.Text;
Response.Cookies.Add(cookie);
Label1.Text = "Cookie Created.....
";
Label1.Text += "New user: " + cookie["Name"];
}
}
Finally run your project to see the result.
Regards
Happy coding