Friday, March 28, 2014

Cookies in ASP.NET C#

To store website's data into browser we use cookies. Today in this example we will learn how to store cookies into your browser by using C# in your ASP.NET project.

For this you need to know about class HttpCookie. Its under System.Web. For more info you can go here.

First we will check how to store the cookies into browser.

So, open a new project, named it as Cookies_Demo and add a new form into it.

Now create a simple log in form like this one.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Cookies Demo</h1>
    <div>
        <asp:TextBox ID="txtEmail" runat="server" placeholder="Email"></asp:TextBox>
        <br />
        <asp:TextBox ID="txtPass" runat="server" placeholder="Password" TextMode="Password"></asp:TextBox>
        <br />
        <asp:CheckBox ID="ckbRememberMe" runat="server" Text="Remember me" />
        <asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click" />
    </div>
    </div>
    </form>
</body>
</html>

It will look like..


Now on button click write the code to store cookies into the user's browser.

/* Store Cookies into browser here at login time */
                /* Place into Coockies */
                //Creting a Cookie Object
                HttpCookie _userInfoCookies = new HttpCookie("UserInfoDemo");

                //Setting values inside it
                _userInfoCookies["EmailDemo"] = txtEmail.Text.Trim();
                _userInfoCookies["PasswordDemo"] = txtPass.Text.Trim();
                //Adding Expire Time of cookies
                _userInfoCookies.Expires = DateTime.Now.AddDays(10);

                //Adding cookies to current web response
                Response.Cookies.Add(_userInfoCookies);

It will store your data into browser for 10 days as a name of  "userInfoCookies".

Now its time to get the data of cookies while we are opening the page. So write down the code in the Page_Load event.

if (HttpContext.Current.Request.Cookies["UserInfodemo"] != null)
                {
                    string email = Request.Cookies["UserInfoDemo"]["EmailDemo"].ToString();
                    txtEmail.Attributes.Add("value", email);

                    string pass = Request.Cookies["UserInfoDemo"]["PasswordDemo"].ToString();
                    txtPass.Attributes.Add("value",pass);
                }
                else if (HttpContext.Current.Request.Cookies["UserInfoDemo"] == null)
                {
                    txtEmail.Text = "";
                }

It will check for the cookies present in the browser and if found then put the value into the text boxes. After this when you will run it you will get a form with value in the text boxes.


You can download the full source code from here.

0 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews