asp.net ajax实现(—):Jquery+Json
适合轻量级的应用,客户端序列化和反序列化可用Json的JSON.parse()和JSON.stringify(),
但服务端序列化和反序列化的时候,遇到一些问题,我采用了三种方式,其中三种方式序列化和反序列化的方式各有不同,比较请点这里看。
以下是我的操作的代码:
前台:
Code
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml" >
3<head runat="server">
4 <title>无标题页</title>
5 <script type="text/javascript" src="../JS/jquery-1.3.min.js"></script>
6 <script type="text/javascript" src="../JS/json2.js"></script>
7 <script type="text/javascript">
8 function GetValue()
9 {
10 $.get("Process.aspx", {Action:"get"}, function (data, textStatus){
11 var name=$("#TName")[0];
12 var address=$("#TAddress")[0];
13 var age=$("#TAge")[0];
14 var obj=JSON.parse(data);
15 name.value=obj.Name;
16 address.value=obj.Address;
17 age.value=obj.Age;
18 });
19 }
20
21 function SetValue()
22 {
23 var person=new Person($("#TName")[0].value,$("#TAddress")[0].value,$("#TAge")[0].value);
24 var str=JSON.stringify(person);
25 alert(str);
26 $.post("Process.aspx", {Action:"post",JsonStr:""+ str +""}, function (data, textStatus){
27 alert("发送成功");
28 });
29 }
30
31 function Person(name,address)
32 {
33 this.Name=name;
34 this.Address=address;
35 }
36 </script>
37</head>
38<body>
39 <form id="form1" runat="server">
40 <div>
41 <table>
42 <tr>
43 <td>姓名:</td>
44 <td><input type="text" id="TName" /></td>
45 </tr>
46 <tr>
47 <td>住址:</td>
48 <td><input type="text" id="TAddress"/></td>
49 </tr>
50 <tr>
51 <td>年龄:</td>
52 <td><input type="text" id="TAge" /></td>
53 </tr>
54 </table>
55 <table>
56 <tr>
57 <td><input type="button" onclick="GetValue();" value="加载数据"></td>
58 <td><input type="button" value="更新数据" onclick="SetValue()"></td>
59 </tr>
60 </table>
61 </div>
62 </form>
63</body>
64</html>
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml" >
3<head runat="server">
4 <title>无标题页</title>
5 <script type="text/javascript" src="../JS/jquery-1.3.min.js"></script>
6 <script type="text/javascript" src="../JS/json2.js"></script>
7 <script type="text/javascript">
8 function GetValue()
9 {
10 $.get("Process.aspx", {Action:"get"}, function (data, textStatus){
11 var name=$("#TName")[0];
12 var address=$("#TAddress")[0];
13 var age=$("#TAge")[0];
14 var obj=JSON.parse(data);
15 name.value=obj.Name;
16 address.value=obj.Address;
17 age.value=obj.Age;
18 });
19 }
20
21 function SetValue()
22 {
23 var person=new Person($("#TName")[0].value,$("#TAddress")[0].value,$("#TAge")[0].value);
24 var str=JSON.stringify(person);
25 alert(str);
26 $.post("Process.aspx", {Action:"post",JsonStr:""+ str +""}, function (data, textStatus){
27 alert("发送成功");
28 });
29 }
30
31 function Person(name,address)
32 {
33 this.Name=name;
34 this.Address=address;
35 }
36 </script>
37</head>
38<body>
39 <form id="form1" runat="server">
40 <div>
41 <table>
42 <tr>
43 <td>姓名:</td>
44 <td><input type="text" id="TName" /></td>
45 </tr>
46 <tr>
47 <td>住址:</td>
48 <td><input type="text" id="TAddress"/></td>
49 </tr>
50 <tr>
51 <td>年龄:</td>
52 <td><input type="text" id="TAge" /></td>
53 </tr>
54 </table>
55 <table>
56 <tr>
57 <td><input type="button" onclick="GetValue();" value="加载数据"></td>
58 <td><input type="button" value="更新数据" onclick="SetValue()"></td>
59 </tr>
60 </table>
61 </div>
62 </form>
63</body>
64</html>
后台:
Code
1 using System;
2 using System.Collections;
3 using System.Configuration;
4 using System.Data;
5 using System.Linq;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13 using System.Runtime.Serialization.Json;
14 using System.ServiceModel.Dispatcher;
15 using System.Text;
16 using System.Web.Script.Serialization;
17 using System.IO;
18 using System.Runtime.Serialization;
19 namespace WebDemo.AjaxTest
20 {
21 public partial class Process : System.Web.UI.Page
22 {
23 protected void Page_Load(object sender, EventArgs e)
24 {
25 if (!Request.Params.AllKeys.Contains("JsonStr"))
26 {
27 GetData();
28 }
29 else
30 {
31 LoadData();
32 }
33 }
34 /// <summary>
35 /// 从客户端加载数据
36 /// </summary>
37 private void LoadData()
38 {
39 string str = Request.Params["JsonStr"];
40 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Model.User));
41 MemoryStream ms=new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()));
42 Model.User user = (Model.User)serializer.ReadObject(ms);
43 ms.Close();
44 }
45 /// <summary>
46 /// 向客户端发送数据
47 /// </summary>
48 private void GetData()
49 {
50 Model.User user = new Model.User();
51 user.Address = "上海市闵行区";
52 user.Age = 26;
53 user.Name = "Windstore";
54 string resultStr;
55 //方式一:System.Runtime.Serialization.Json Assembly:System.ServiceModel.Web
56 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Model.User));
57 MemoryStream stream = new MemoryStream();
58 serializer.WriteObject(stream, user);
59 stream.Position = 0;
60 StreamReader sr = new StreamReader(stream);
61 resultStr = sr.ReadToEnd();
62 sr.Close();
63 stream.Close();
64 //方式二:System.ServiceModel.Dispatcher.JsonQueryStringConverter Assembly:System.ServiceModel
65 //JsonQueryStringConverter convert = new JsonQueryStringConverter();
66 //resultStr = convert.ConvertValueToString(user, typeof(Model.User));
67 //方式三:System.Web.Script.Serialization
68 //StringBuilder sb = new StringBuilder();
69 //JavaScriptSerializer jsServilizer = new JavaScriptSerializer();
70 //jsServilizer.Serialize(user, sb);
71 //resultStr = sb.ToString();
72 Response.ContentType = "application/json";
73 Response.Write(resultStr);
74 Response.Flush();
75 Response.End();
76 }
77 }
78 }
79
1 using System;
2 using System.Collections;
3 using System.Configuration;
4 using System.Data;
5 using System.Linq;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13 using System.Runtime.Serialization.Json;
14 using System.ServiceModel.Dispatcher;
15 using System.Text;
16 using System.Web.Script.Serialization;
17 using System.IO;
18 using System.Runtime.Serialization;
19 namespace WebDemo.AjaxTest
20 {
21 public partial class Process : System.Web.UI.Page
22 {
23 protected void Page_Load(object sender, EventArgs e)
24 {
25 if (!Request.Params.AllKeys.Contains("JsonStr"))
26 {
27 GetData();
28 }
29 else
30 {
31 LoadData();
32 }
33 }
34 /// <summary>
35 /// 从客户端加载数据
36 /// </summary>
37 private void LoadData()
38 {
39 string str = Request.Params["JsonStr"];
40 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Model.User));
41 MemoryStream ms=new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()));
42 Model.User user = (Model.User)serializer.ReadObject(ms);
43 ms.Close();
44 }
45 /// <summary>
46 /// 向客户端发送数据
47 /// </summary>
48 private void GetData()
49 {
50 Model.User user = new Model.User();
51 user.Address = "上海市闵行区";
52 user.Age = 26;
53 user.Name = "Windstore";
54 string resultStr;
55 //方式一:System.Runtime.Serialization.Json Assembly:System.ServiceModel.Web
56 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Model.User));
57 MemoryStream stream = new MemoryStream();
58 serializer.WriteObject(stream, user);
59 stream.Position = 0;
60 StreamReader sr = new StreamReader(stream);
61 resultStr = sr.ReadToEnd();
62 sr.Close();
63 stream.Close();
64 //方式二:System.ServiceModel.Dispatcher.JsonQueryStringConverter Assembly:System.ServiceModel
65 //JsonQueryStringConverter convert = new JsonQueryStringConverter();
66 //resultStr = convert.ConvertValueToString(user, typeof(Model.User));
67 //方式三:System.Web.Script.Serialization
68 //StringBuilder sb = new StringBuilder();
69 //JavaScriptSerializer jsServilizer = new JavaScriptSerializer();
70 //jsServilizer.Serialize(user, sb);
71 //resultStr = sb.ToString();
72 Response.ContentType = "application/json";
73 Response.Write(resultStr);
74 Response.Flush();
75 Response.End();
76 }
77 }
78 }
79
Model类:
Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Runtime.Serialization;
6 namespace WebDemo.Model
7 {
8 /// <summary>
9 /// 用户实体
10 /// </summary>
11 [DataContract]
12 public class User
13 {
14 #region 私有字段
15 private string named;
16 private string addressd;
17 private int aged;
18 #endregion
19 #region 公共属性
20 /// <summary>
21 /// 姓名
22 /// </summary>
23 [DataMember]
24 public string Name
25 {
26 get { return named; }
27 set { named = value; }
28 }
29
30 /// <summary>
31 /// 家庭住址
32 /// </summary>
33 [DataMember]
34 public string Address
35 {
36 get { return addressd; }
37 set { addressd = value; }
38 }
39
40 /// <summary>
41 /// 年龄
42 /// </summary>
43 [DataMember]
44 public int Age
45 {
46 get { return aged; }
47 set { aged = value; }
48 }
49 #endregion
50 }
51 }
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Runtime.Serialization;
6 namespace WebDemo.Model
7 {
8 /// <summary>
9 /// 用户实体
10 /// </summary>
11 [DataContract]
12 public class User
13 {
14 #region 私有字段
15 private string named;
16 private string addressd;
17 private int aged;
18 #endregion
19 #region 公共属性
20 /// <summary>
21 /// 姓名
22 /// </summary>
23 [DataMember]
24 public string Name
25 {
26 get { return named; }
27 set { named = value; }
28 }
29
30 /// <summary>
31 /// 家庭住址
32 /// </summary>
33 [DataMember]
34 public string Address
35 {
36 get { return addressd; }
37 set { addressd = value; }
38 }
39
40 /// <summary>
41 /// 年龄
42 /// </summary>
43 [DataMember]
44 public int Age
45 {
46 get { return aged; }
47 set { aged = value; }
48 }
49 #endregion
50 }
51 }
客户端用JSON.stringify()反序列化的时候,默认的值都是字符串类型的,如果想返回整型值,可以用 JSON.stringify(myObject, replacer);用回调函数replacer处理。