【问题标题】:Jquery ajax using webservice to return jsonJquery ajax使用webservice返回json
【发布时间】: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 我更新了我的问题

标签: jquery ajax json wcf


【解决方案1】:

为webmethod的返回类型创建一个类,例如,

class Person
{
    public int ID { get; set; }
    public string Value { get; set; }
}

那你就可以这样写webmethod了,

public Person GetPerson()
{
    Person person = new Person();
    person.ID = 1;
    person.Value = "test";
    return person;

}

然后在 ajax 成功后,你会得到格式正确的 json 响应。

【讨论】:

猜你喜欢
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 1970-01-01
  • 2012-06-24
  • 2014-02-03
  • 2013-07-28
相关资源
最近更新 更多