我有一个操作契约接受一个复杂的对象,我通过jQuery调用该操作.如何使用jQuery传入类似于复杂类型的对象.以下是操作签名:
public Resolution CreateNewResolution(Resolution NewResolution);
Run Code Online (Sandbox Code Playgroud)
我需要在客户端传递一个Resolution对象,但我不知道如何使用jQuery.有帮助吗?
谢谢
Che*_*eso 22
虽然我不同意他对GET的使用,并且在复杂参数的查询字符串中传递JSON,但请参阅Denny的帖子.这似乎是错的.
您使用的参数data是您的Resolution类型的json表示.例如,假设类型和操作在服务器端定义如下:
[DataContract( Namespace = "urn:brandon.michael.hunter/ws/2010/01",
Name = "Resolution" )]
public class Resolution
{
[DataMember( IsRequired = true, Name = "Name" )]
public string Name { get; set; }
[DataMember( IsRequired = true, Name = "Rank" )]
public int Rank { get; set; }
[DataMember( IsRequired = true, Name = "SerialNumber" )]
public int SerialNumber { get; set; }
[DataMember( IsRequired = false, Name = "Id" )]
public int Id { get; set; }
}
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "new")]
public Resolution CreateNewResolution(Resolution r)
{
// your logic here
r.Id = System.Guid.NewGuid();
return r;
}
Run Code Online (Sandbox Code Playgroud)
然后,在Javascript中,您使用的代码可能如下所示:
var resolution = {r: { Name : "Fred", Rank : 2, SerialNumber : 17268 }};
// convert object to JSON string (See http://jollytoad.googlepages.com/json.js)
var objectAsJson = $.toJSON(resolution);
// result is a string: '{"Name":"Fred","Rank":"2","SerialNumber":"17268"}'
$.ajax({
type : "PUT", // must match Method in WebInvoke
contentType : "application/json",
url : "Service.svc/new", // must match UriTemplate in WebInvoke
data : objectAsJson,
dataFilter : function (data, type) {
// convert from "\/Date(nnnn)\/" to "new Date(nnnn)"
return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
},
processData : false, // do not convert outbound data to string (already done)
success : function(msg){ ... },
error : function(xhr, textStatus, errorThrown){ ... }
});
Run Code Online (Sandbox Code Playgroud)
笔记:
processData=true,那么发送到服务的结果字符串是查询字符串格式,而不是JSON格式.不是我想传递复杂对象的东西.所以我把它设置为假.对于您正在进行WebGet的简单非JSON请求,使用true将是正常的,并且所有参数都在查询字符串中.msg传递给成功回调的参数包含返回的json.| 归档时间: |
|
| 查看次数: |
29678 次 |
| 最近记录: |