Monday, 20 July 2015

Cookies Example in Asp.net C#

Step:1 Create a new website page

Step:2 Select an Empty Web Site

Step:3 Go to Solution Explorer and Right Click now click on Add items and select n Form and Name it its default name is Default.aspx. put one image to display as i put in below as christmas-110v.jpg and like.jpg is for like button and unlike.jpg is for unlike image .

Step:4 Coding on default.aspx.cs file
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

     
   
        if (Request .Cookies ["like"]!=null && Request .Cookies ["unlike"]!=null )
        {
            Label1.Text = Request.Cookies["like"].Values["u1"].ToString();
            Label2.Text = Request.Cookies["unlike"].Values["u2"].ToString();
         
        }

     
    }
 
    protected void Button1_Click(object sender, EventArgs e)
    {
     
        HttpCookie c1 = new HttpCookie("like");
        c1.Values.Add("u1", Convert.ToString(Convert.ToInt32(Label1.Text) + 1));
        c1.Expires = System.DateTime.Now.AddDays(30);
        Response.Cookies.Add(c1);
        Response.Redirect(Request.RawUrl);
     
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

     

        HttpCookie c2 = new HttpCookie("unlike");
        c2.Values.Add("u2", Convert.ToString(Convert.ToInt32(Label2.Text) + 1));
        c2.Expires = System.DateTime.Now.AddDays(30);
        Response.Cookies.Add(c2);
        Response.Redirect(Request.RawUrl);
     
    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {

    }
    protected void ImageButton1_Click1(object sender, ImageClickEventArgs e)
    {

    }
}

Step:5 Save it and run it 

No comments:

Post a Comment