[ScriptMethod (ResponseFormat = ResponseFormat.Json)]

In ASP.net web service, if the above is not specified, what is the default response format? Also, if my web service is below:

[WebMethod()] public List<Sample> GenerateSamples(string[][] data) { ResultsFactory f = new ResultsFactory(data); List<Sample> samples = f.GenerateSamples(); return samples; } 

returns a list of objects. If I change the response format to JSON, I need to change the return type to string, then how do I access the objects in my javascript?

I am currently calling this web service in my JS, for example:

  $.ajax({ type: "POST", url: "http://localhost/TemplateWebService/Service.asmx/GenerateSamples", data: jsonText, contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { var samples = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d; if (samples.length > 0) { doSomethingHere(samples); } else { alert("No samples have been generated"); } }, error: function(xhr, status, error) { var msg = JSON.parse(xhr.responseText); alert(msg.Message); } }); 

What I noticed though, although everything works fine, the eval instruction never starts, which means the web service always returns a string!

So my question is that [ScriptMethod (ResponseFormat = ResponseFormat.Json)] is needed on the side of the web service definition?

Now all I can do, I can use an array of samples and access to each object and its properties, as usual, in any OOP code, which is very convenient and everything does not work, but I just wanted to make sure that I didn’t missed in my setup.

I took the basics of combining Jquery ajax with asp.net from Encosia, and the type of response was not mentioned there - I read it on another site, and I'm not sure how vital it is.

http://www.codeproject.com/KB/webservices/JsonWebServiceJQuery.aspx

Lists 4 different changes on the asp.net web service side. I have only the first 2 - in my web.config. The service itself and the Sample class are implemented without any serialization, but it does have properties. I assume the default JSON web service? And as long as your objects have properties, are they serialized by default? That was my understanding until I read this article.

+6
jquery ajax web-services
source share
1 answer

The ResponseFormat attribute is not required. Including client and server settings, this requires only four things:

  • Add ScriptHandlerFactory HttpHandler to your web.config.
  • Decorate your web services with the [ScriptService] attribute.
  • Request maintenance methods using the POST verb.
  • Request service methods with content type "application / json".

When you do these four things, service method responses will be automatically serialized as JSON.

+6
source share

All Articles