序列化上面创建的Person对象,使其成为一个JSON字符串

<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Sample.aspx.cs"
    Inherits="ClientScripting_SysSerialization_Sample" Title="Sys.Serialization命名空间下的类" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

    <script runat="Server">
        protected void Button1_Click(object sender, EventArgs e)
        {
            // 创建一个Person对象
            Person person = new Person();
            person.Name = "webabcd";
            person.Age = 27;

            // 序列化上面创建的Person对象,使其成为一个JSON字符串
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            string s = jss.Serialize(person);
            // 注册DataItem
            ScriptManager.GetCurrent(this).RegisterDataItem(this.UpdatePanel1, s);
        }

        /// <summary>
        /// Person类
        /// </summary>
        public class Person
        {
            private string _name;
            /// <summary>
            /// 姓名
            /// </summary>
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }

            private int _age;
            /// <summary>
            /// 年龄
            /// </summary>
            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }

        }
    </script>

    <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="Server">
        <ContentTemplate>
            <%= DateTime.Now.ToString()%>
            <br />
            <asp:Button ID="Button1" runat="server" Text="Sys.Serialization" OnClick="Button1_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <p>
        <textarea id="TraceConsole" style="width: 500px; height: 100px;"></textarea>
    </p>

    <script language="javascript" type="text/javascript">

        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
        function endRequestHandler(sender, e)
        {
            var upId = "<%= this.UpdatePanel1.ClientID %>";
            // 获得服务端注册的DataItem,它是一个JSON字符串
            var jsonStringServer = e.get_dataItems()[upId];
            // 反序列化这个JSON字符串,使其成为一个JSON对象
            var jsonObject = Sys.Serialization.JavaScriptSerializer.deserialize(jsonStringServer)

            // 序列化这个JOSN对象,使其成为一个JSON字符串
            var jsonStringClient = Sys.Serialization.JavaScriptSerializer.serialize(jsonObject);
            Sys.Debug.trace(jsonStringClient);
            Sys.Debug.trace(jsonObject.Name + " " + jsonObject.Age);
            Sys.Debug.trace(Sys.Serialization.JavaScriptSerializer.serialize(jsonObject));
        }

    </script>

</asp:Content>

posted @ 2009-08-12 15:38  汉卿  Views(545)  Comments(0Edit  收藏  举报