Cookies in asp.net(inserting and fetching cookies)  

by ne on 2021-03-02 under Asp.net

Create a page named page1.aspx, and then drag a button and a TextBox onto the page.

Double click the button and then add the following code:

protected void Button1_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = new HttpCookie("UserName");
        cookie.Value = TextBox1.Text;
        cookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(cookie);
        Response.Redirect("Page2.aspx");
    }


page1.aspx,


         <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  

above code will create the cookies. now add a new page "page2.aspx" On page2.aspx, double click the form and put the following code in it:

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["UserName"] != null)
            Response.Write(Request.Cookies["UserName"].Value);
    }

on above page you will get the cookies which you have inserted or created on previous page. :) thanks