Asp.net Ajax WebService开发文档
基础使用
1 新建一个解决方案,右键解决方案名称选择“添加—新建网站”,新建一个asp.net 网站WebSite1,右键Website1,选择“添加新项—Web服务”,添加一个Web服务WebService1。则在跟目录下生成WebService1.asmx,App_Code文件夹中生成WebService1.cs。在WebService1.cs文件中,已经生成一个web方法HelloWorld如下:
/// <summary>
/// 返回字符串
/// </summary>
/// <returns></returns>
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
注意:将被注释的[System.Web.Script.Services.ScriptService]取消注释。
2 新建一个web窗体,添加ScriptManage组件,配置如下:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService1.asmx"/>
</Services>
</asp:ScriptManager>
则在js中调用此web服务的方式为:
WebService.HelloWorld( function sucess(res){alert(res);},
function failed(res){alert(res);},
"调用web服务");
3 使用Web方法返回单个Json对象
新建一个Student类,包含SName,SSex,IAge三个属性。在WebService1.cs文件中创建如下方法:
…
using System.Web.Script.Services;
…
/// <summary>
/// 返回单个Json对象
/// </summary>
/// <returns></returns>
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Student ShowInfo()
{
return new Student("zww","man",26);
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]的作用是将Student对象序列化为Json对象,以便在页面上可使用js操作。
则在页面上使用此Web服务的方式为:
WebService.ShowInfo(function(res)
{
if(res==null)return ;
alert(res.SName);
});
注:Json对象和Json格式字符串相互转换的使用方法如下,
WebService.ShowInfo(function(res)
{
if(res==null)return ;
//将json对象序列化为字符串
var personStr = Sys.Serialization.JavaScriptSerializer.serialize(res);
alert(personStr);//{"__type":"Student","SName":"zww","SSex":"man","IAge","26"}
//将字符串反序列化为json对象
var person = Sys.Serialization.JavaScriptSerializer.deserialize(personStr,true);
alert(person);//[object Object]
//从WebService传递的已经为json对象,直接使用“对象名.属性名”访问
alert(res.SName);//zww
//var str = '{name:"zww",sex:"man",color:"yellow"}';
//var person = eval('('+ str +')');
});
4 使用Web方法返回单个Json对象(使用list容器)
…
using System.Web.Script.Services;
…
/// <summary>
/// 返回多个json对象
/// </summary>
/// <returns></returns>
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Student> GetAll()
{
List<Student> list = new List<Student>();
Student s1 = new Student("tom", "man", 26);
Student s2 = new Student("mary", "woman", 22);
list.Add(s1);
list.Add(s2);
return list;
}
则在页面上使用此Web服务的方式为:
//操作存放具体对象的list容器对象
WebService.GetAll(function(res)
{
if(res==null){return;}
var content = "";
for(var i=0;i<res.length;i++)
{
content = content + res[i].SName + "<br/>";
}
document.getElementById("info").innerHTML += content;
});
5 使用自定义序列化方式(将数据记录DataTable转换为Json对象)
实现将DataTable转换为Json对象的类如下:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.Web.Script.Serialization;
/// <summary>
///MyJSONs 的摘要说明
/// </summary>
namespace ZWW.Utility
{
public class DataTableConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get
{
return new Type[] { typeof(DataTable) };
}
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
DataTable listType = obj as DataTable;
if (listType != null)
{
// Create the representation.
Dictionary<string, object> result = new Dictionary<string, object>();
ArrayList itemsList = new ArrayList();
foreach (DataRow row in listType.Rows)
{
//Add each entry to the dictionary.
Dictionary<string, object> listDict = new Dictionary<string, object>();
foreach (DataColumn dc in listType.Columns)
{
listDict.Add(dc.ColumnName, row[dc]);
}
itemsList.Add(listDict);
}
result["Rows"] = itemsList;
return result;
}
return new Dictionary<string, object>();
}
}
}
将此类文件存放在App_Code文件夹下,并在web.config文件中添加如下项:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="1024000">
<converters>
<add name ="DataTableConverter" type=" ZWW.Utility.DataTableConverter"/>
</converters>
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
在WebService1.cs中创建如下方法:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public DataTable QueryAll()
{
return DB.QueryAll().Tables[0];
}
其中DB.QueryAll()返回类型为DataSet。
则在页面上调用此Web服务的方式为:
//直接操作json后的DataTable
WebService.QueryAll (function(res)
{
if(res==null){return;}
var content = "";
for(var i=0;i<res.Rows.length;i++)
{
content = content + res.Rows[i]["code"] + "<br/>";
}
document.getElementById("info").innerHTML += content;
});
这里就介绍这么几点,还有其他更加高级的使用方法需要慢慢学习。如有错误疏漏,请大家指正说明,谢谢。
左伟伟
2009年2月11日星期三