第一步:自定义数据类型(最终此类型以JSON的格式返回到客户端供解析)
JsonResult.cs 文件代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
[DataContract]
public class JsonResult
{
public
JsonResult(string name, string address, string phone)
{
_name = name ;
_address = address;
_phone = phone;
}
private
string _name;
[DataMember]
public
string Name
{
get { return _name; }
set { _name = value; }
}
private
string _address;
[DataMember]
public
string Address
{
get { return _address; }
set { _address = value; }
}
private
string _phone;
[DataMember]
public
string Phone
{
get { return _phone; }
set { _phone = value; }
}
}
第二步:构建wcf服务
Service.svc 文件代码:
Service="Service" CodeBehind="~/App_Code/Service.cs"
%>
IService.cs 文件代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(ResponseFormat =
WebMessageFormat.Json, BodyStyle =
WebMessageBodyStyle.Wrapped)]
JsonResult
GetJsonResult(string name, string address, string phone);
}
Service.cs 文件代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
public class Service : IService
{
public
JsonResult GetJsonResult(string name, string address, string
phone)
{
JsonResult result = new JsonResult(name, address, phone);
return result;
}
}
第三步:客户端调用wcf服务,并读取自定义数据类型(在客户端以JSON格式返回)
function
Call() {
$("#divMessagePanel").html("");
var formativeData =
'{"name":"张三","address":"李四","phone":"王五"}';
$.ajax({
type: "post",
url: "../Service.svc/ajaxEndpoint/GetJsonResult",
contentType: "application/json;charset=utf-8",
data: formativeData,
success: function(data) {
alert(data);
var a = eval_r('(' + data +
')'); alert(a.GetJsonResultResult.Name);
$('#divMessagePanel').html("ok");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$("#divMessagePanel").html("error");
},
cache: false
});
}
web.config中wcf的配置部分:
name="jsonWcfBehavior">
name="Service">
address="ajaxEndpoint"
behaviorConfiguration="jsonWcfBehavior"
binding="webHttpBinding"
contract="IService">