1、第一步创建wcf服务的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
[ServiceContract(Namespace = "Valsun", Name = "Service1")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class HelloWorldService
{
// 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
// 要创建返回 XML 的操作,
// 请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// 并在操作正文中包括以下行:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public string HelloWorld()
{
// 在此处添加操作实现
return "你好好好啊好";
}
// 在此处添加更多操作并使用 [OperationContract] 标记它们
[OperationContract]
public Dictionary<string, string> GetTestList(string id)
{
// 定义一个字典对象
Dictionary<string, string> dic = new Dictionary<string, string>();
// 方便测试,直接构造一些数据来模拟数据库中的数据
dic.Add("1" + id, "上海");
dic.Add("2" + id, "北京");
dic.Add("3" + id, "广州");
dic.Add("4" + id, "深圳");
dic.Add("5" + id, "南京");
// 返回值
return dic;
}
}
}
第二步 创建页面调用方法
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <!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>Index</title>
<script src="<%= Url.Content("~/Scripts/jquery-1.4..js") %>"
type="text/javascript"></script> </head>
<body> <form id="form1" runat="server">
<div> <br />
<br />
<input id="btnQueryDictionary" type="button" value="测试" onclick="btnQuery();" />
<br />
<br />
消息: <p id="lblMsg"></p>
</div> <script type="text/javascript">
function btnQuery() { var id = "";
var wcfProxy = new Valsun.Service1();
wcfProxy.GetTestList(id, OnSucceededCallback, OnFailedCallback);
}
function OnSucceededCallback(result, userContext, methodName) {
if (methodName == "GetTestList") {
var msg = "";
// 注意这里的访问方式!!!
for (var key in result) {
msg += result[key].Key + " : " + result[key].Value + "\n";
}
$("#lblMsg").html(msg) ;
}
}
function OnFailedCallback(error, userContext, methodName) {
alert("异常信息:" + error.get_message() + "\n" +
"异常类型:" + error.get_exceptionType() + "\n" +
"堆栈信息:" + error.get_stackTrace());
}
</script> <asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="http://localhost:2813/HelloWorldService.svc" />
</Services>
</asp:ScriptManager>
</form> </body>
</html>
返回的是字典集合,很简单,我放错的原因是写错了一个单词,这个是用jquery实现的