1

Hey guys Its a simple question but want to stop ajax return object contains d.

I asp.net web form

    $.ajax({
        type: "POST",
        url: myurl,
        data: JSON.stringify({value:"1"}),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            //alert("i am in success");
            console.log(result);

        },
        failure: function (response) {
            console.log("I am in failure");
        }
    });

and in .cs file

        [WebMethod]

        public static string getSpareParts(string value)
        {
            List<data> spareParts;
            using (var db = new WaltonCrmEntities())
            {
                spareParts = db.SpareParts.Select(x => new data
                {
                    id = x.ItemID,
                    text = x.ItemName
                }).ToList();
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Serialize(spareParts);
            //return spareParts;

        }

when result is return it will contain result in result.d but i want to stop this d thing .Simply result should be the result. Can anybody solve this.

Syed Mhamudul Hasan
  • 1,341
  • 2
  • 17
  • 45

1 Answers1

4

There's not much you could do about this. That's the way ASP.NET WebMethods always serialize the response. The reason why Microsoft decided to wrap the response in this .d property is to protect against this particular JSON hijacking vulnerability. Of course you could always check in your success callback whether this property is present or not:

success: function (result) {
    var data = result.hasOwnProperty('d') ? result.d : result;
    console.log(data);
}

Also I would very strongly recommend against writing plumbing code in your WebMethod (like serialization stuff) and just return the proper object and let the infrastructure care about serialization:

[WebMethod]
public static List<data> getSpareParts(string value)
{
    using (var db = new WaltonCrmEntities())
    {
        return db.SpareParts.Select(x => new data
        {
            id = x.ItemID,
            text = x.ItemName
        }).ToList();
    }
}

Now inside your success callback you can directly work with this collection without the need to additionally JSON.parse it:

success: function (result) {
    var data = result.hasOwnProperty('d') ? result.d : result;
    for (var i = 0; i < data.length; i++) {
        console.log('id: ' + data[i].id + ', text: ' + data[i].text);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928