.net framework 3.5 利用asmx文件,向前台页面传递JSON字符串。

利用asmx文件 向前台页面发送JSON字符串
1.前台页面代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jQuery_jSON._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script type="text/javascript"  src="JS/jquery.js"></script>
    <script type="text/javascript"  src="JS/AJAX_jSON.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Scripts>
    <asp:ScriptReference Path="~/JS/jquery.js" />
    <asp:ScriptReference Path="~/JS/AJAX_jSON.js" /> 
    </Scripts>
    <Services>
    <asp:ServiceReference Path="~/services/WebService1.asmx" />
    </Services>
    </asp:ScriptManager>
    <div>
    <input type="button" value="调用webServices序列化JSON对象" id="btn1"/><br />
    姓名:<input type="text" id="name"/><br />
    年龄:<input type="text" id="age" /><br/>
    性别:<input type="text" id="sex" /><br />
    <input type="button" value="反序列化JSON对象" id="btn2"/>
    </div>
    </form>
</body>
</html>


2.创建对象实体类

    public  class  User
    {
        private string name;

        private string sex;

        private int age;

        public int Age
        {
          get { return age; }
          set { age = value; }
        }

        public string Sex
        {
          get { return sex; }
          set { sex = value; }
        }
       
        public string Name
        {
          get { return name; }
          set { name = value; }
        }
    }


3.创建 asmx文件

  [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        //对象序列化成JSON字符串
        [WebMethod]
        public string GetUser()
        {
            User user = new User();
            user.Name = "michael";
            user.Sex = "man";
            user.Age = 26;

            #region 将对象序列化成JSON字符串返回页面
            var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            if (user != null)
            {
                return jss.Serialize(user);
            }
            else
            {
                return null;
            }
            #endregion
        }

        [WebMethod]
        public void CreateUser(string user)
        {
            User u = (User)this.SetUser<User>(user);
            string test = u.Age + u.Name + u.Sex;
        }

        // JSON字符串反序列化成对象
        public T SetUser<T>(string user)
        {
            #region 将JSON字符串反序列化成对象
            var obj = new System.Web.Script.Serialization.JavaScriptSerializer();
            try
            {
                return obj.Deserialize<T>(user);
            }
            catch (Exception ex)
            {
                return default(T);
            }
            #endregion
        }

    }
  }

4.编写JS文件代码


$(document).ready(function() {
    $("#btn1").click(function() {
        //调用webServices返回JSON字符串
        jQuery_jSON.services.WebService1.GetUser(disp);
    });
    //json对象显示
    function disp(result) {
        var json = eval('(' + result + ')');
        alert("姓名:" + json.Name + " 性别:" + json.Sex + "  年龄:" + json.Age);
    }

    $("#btn2").click(function() {
        var name = $("#name").attr("value");
        var age = $("#age").attr("value");
        var sex = $("#sex").attr("value");
        var user = "{\"Name\": " + name + ", \"Age\": " + age + ", \"Sex\": " + sex + " }";
        //调用webService
        jQuery_jSON.services.WebService1.CreateUser(user);
    });
});

5补充:如果asmx文件中序列化对象集合   

 //将对象集合序列化成JSON字符串
        [WebMethod]
        public string SeriersUser()
        {
            User user1 = new User();
            user1.Name = "michael";
            user1.Sex = "man";
            user1.Age = 26;

            User user2 = new User();
            user2.Name = "Ramy";
            user2.Sex = "women";
            user2.Age = 26;

            User[] user = { user1,user2};
            //序列化JSON字符串
            var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            return jss.Serialize(user);
        }
     JS代码
     //显示对象集合
    $("#btn3").click(function() {
        jQuery_jSON.services.WebService1.SeriersUser(disp1);
    });

    function disp1(result) {
        alert( result );
        var jss = eval(result);
        for (var i = 0; i < jss.length; i++) {
            alert(jss[i].Name + "|" + jss[i].Sex + "|" + jss[i].Age);
        }
    }




 

 



 

posted @ 2009-09-01 15:41  狗狗听话  阅读(1311)  评论(0编辑  收藏  举报