【发布时间】:2014-05-21 08:03:48
【问题描述】:
我想使用 jquery ajax 调用从 c# .net 返回 json 数据。现在由于我想返回 json,我正在考虑使用 WCF 或使用页面方法作为 WebMethod。
从我尝试使用页面 WebMethod 的结果来看,我收到以下响应“as”json:
{"d":"{\"ID\":1,\"Value\":\"第一个值\"}"}
这是一个正确的 json,还是有办法使用 WCF 获得一个“干净”的 json?
ajax
$.ajax({
type: 'POST',
url: 'Service1.svc/DoWork',
cache: false,
contentType: "application/json; charset=utf-8",
data: "{ }",
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (xhr, msg, msg2) {
alert(msg);
}
});
WCF
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
[OperationContract]
public List<TestClass> DoWork()
{
List<TestClass> tc = new List<TestClass>();
tc.Add(new TestClass() { ID = 1, Value = "First Value" });
return tc;
}
public class TestClass
{
public TestClass()
{ }
public int ID { get; set; }
public string Value { get; set; }
}
}
【问题讨论】:
-
你现在返回字符串吗?
-
@AnoopJoshi 我得到了相同的结果,从 c# 返回字符串或类。在 .ajax 我有 dataType: 'json'
-
你的 wcf webmethod 的返回类型是什么?
-
@AnoopJoshi 我更新了我的问题