1

I want to use jquery ajax call to return json data from c# .net. Now since I want to return json, I am thinking of using WCF or using a page method as WebMethod.

From what I have tried using a page WebMethod i receive the following response "as" json:

{"d":"{\"ID\":1,\"Value\":\"First Value\"}"}

Is this a proper json, or is there a way to get a "clean" json using WCF?

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; }

        }

    }
mko
  • 6,638
  • 12
  • 67
  • 118

1 Answers1

0

Create a class for the return type of webmethod, For example,

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

Then you can write the webmethod like this,

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

}

Then in the ajax success, you will get the correctly formatted json response.

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
  • that is what I am basically doing – mko May 21 '14 at 09:01
  • it returns {"d":[{"__type":"Service1.TestClass:#Admin.Web.Test","ID":1,"Value":"First Value"}]} – mko May 21 '14 at 09:08
  • 1
    check this link http://stackoverflow.com/questions/8437472/how-to-remove-d-and-type-from-json-response-for-asp-web-service – Anoop Joshi P May 21 '14 at 09:10
  • 2
    I have actually found this link to be useful http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/ – mko May 22 '14 at 09:31