C# 和 JavaScript Cookie 共享

iDotNetSpace發表於2009-12-07
cookie.aspx






    myCookieTest
   
        .divRoot
        {
            border: dotted 1px red;
            padding: 20px;
            margin: 20px;
        }
        .divRoot h1
        {
            text-align: center;
            color: Blue;
            background-color:Gray;
        }
        hr
        {
            color: Green;
        }
   

   
        function addCookie(key,value) {
            var expireDate = new Date(); //cookie 有效日期
            expireDate.setMonth(expireDate.getMonth() + 6);
            document.cookie = key+"=" + value + "; expires=" + expireDate.toGMTString();  //新增 cookie
            alert("新增成功~!!");
            return false;
        }

        function getCookie() {
            if (document.cookie != "") {
                document.getElementById("spCookie").innerHTML = document.cookie;
            }
        }
   



   
   

       

           


                JavaScript. -> C#


           


                JavaScript. Add Cookie:


           


                Enter The Cookie Value:
               


       

       

       

           


                C# Get Cookie:


           


                The Cookie Value:
               
               


       

   

   

       

           


                C# -> JavaScript


           


                C# Add Cookie:


           


                Enter The Cookie Value:
               
               


       

       

       

           


                JavaScript. Get Cookie:


           


                The Cookie Value:
               


       

   

   




cookie.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    protected void btnGetCookie_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies.Get("userName");

        if (cookie != null)
        {
            lblCookie.Text = cookie.Value;
        }
        else
        {
            lblCookie.Text = "NULL";
        }
    }
    protected void btnAddCookie_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = new HttpCookie("SharpCookie");
        cookie.Value = txtCookie.Text;
        Response.Cookies.Add(cookie);
        txtCookie.Text = string.Empty;
    }
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-621841/,如需轉載,請註明出處,否則將追究法律責任。

相關文章