ASP.NET & JavaScript 透過Cookie 傳遞JSON

ASP.NET & JavaScript 透過Cookie 傳遞JSON

Technorati 的標籤: ,,,

 

程式流程:

2013-6-21 上午 10-44-27

 

KeyPint:

 

1.將字串轉為JSON

JSON.stringify(personList);

2.將JSON轉回物件

JSON.parse(JSONString)

3.JavaScript建立Cookie 

document.cookie = "myCookie=" + cookieValue;

4.後端取得cookie

HttpCookie cookie = Request.Cookies["myCookie"];

5.後端反序列化JSON

JavaScriptSerializer Serializer = new JavaScriptSerializer();
List<person> personList = Serializer.Deserialize<List<person>>(cookie.Value);

 

前端原始碼:

 

有引用jquery.cookie.js

記得要下載程式才能用!!

<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="../lib/jquery.cookie.js"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {

            $('#btnAddItem').click(function () {
                var personList = new Array();
                var _user = $('#userInput').val();
                var _tel = $('#telInput').val();
                var _age = $('#ageInput').val();
                var personInfo = { user: _user, tel: _tel, age: _age };

                //取回myCookie
                if ($.cookie("myCookie") != null) {
                    personList = JSON.parse($.cookie("myCookie"));
                }

                //personInfo 存入陣列
                personList.push(personInfo);

                //將陣列轉為JSON字串
                var JSON_cookieValue = JSON.stringify(personList);

                var date = new Date();
                date.setTime(date.getTime() + (5 * 60 * 1000));

                //存入myCookie 指定存活時間     
                //$.cookie("myCookie", JSON_cookieValue, { expires: date });

                //存入myCookie 不指定存活時間
                document.cookie = "myCookie=" + JSON_cookieValue;
                //alert(JSON_cookieValue);


                var JSON_cookie = $.cookie("myCookie");
                alert(JSON_cookie);

            });

            $('#clearCookieBtn').click(function () {

                if ($.cookie("myCookie") == null) {
                    return;
                } else {
                    $.cookie("myCookie", null);

                }

            });
        });
    </script>
</head>
<body>

    <form id="form1" runat="server">
        <ul>
            <li>
                <span>姓名</span>
                <input type="text" id="userInput" maxlength="15" value="Sean" />
            </li>
            <li>
                <span>電話</span>
                <input type="text" id="telInput" maxlength="16" value="0933-123456">
            </li>
            <li>
                <span>年齡</span>
                <input type="text" id="ageInput" maxlength="4" value="33">
            </li>
            <li>
                <asp:Button Text="加入一筆資料到cookie" ID="btnAddItem" runat="server" />
                <input type="button" id="clearCookieBtn" value="清除Cookie" />
                <asp:Button Text="把JSON字串轉成List" ID="btn_JSONstrToList" runat="server"
                    OnClick="btn_btn_JSONstrToList_Click" />
            </li>

            <li>
                <span>cookie 內容:   </span>
                <asp:GridView runat="server" ID="GridView1" />
            </li>
        </ul>
    </form>

</body>
</html>

 

後端原始碼:

        /// 接收JSON的類別
        /// </summary>
        public class person
        {
            public string user { get; set; }
            public string tel { get; set; }
            public int age { get; set; }
        }

        //把JSON字串轉成List
        protected void btn_btn_JSONstrToList_Click(object sender, EventArgs e)
        {
            //檢查Cookie是否存在
            if (Request.Cookies["myCookie"] == null)
            {
                Response.Write("cookie沒有資料");
                return;
            }

            //取得Cookie
            HttpCookie cookie = Request.Cookies["myCookie"];

            //反序列化JSON
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<person> personList = Serializer.Deserialize<List<person>>(cookie.Value);

            //用Gridview顯示資料
            GridView1.DataSource = personList;
            GridView1.DataBind();
        }

 

範例檔下載