How to let an ASMX file output JSON
From WebService returns XML even when ResponseFormat set to JSON:
Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.
Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services
How to get JSON response from a 3.5 asmx web service
I faced the same issue, and included the below code to get it work.
[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write("Hello World");
//return "Hello World";
}
Update:
To get a pure json format, you can use javascript serializer like below.
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
HelloWorldData data = new HelloWorldData();
data.Message = "HelloWorld";
Context.Response.Write(js.Serialize(data));
}
}
public class HelloWorldData
{
public String Message;
}
However this works for complex types, but string does not show any difference.
Returning JSON from ASMX, and handling it correctly in Javascript
It seems to me that your main problem that you try to manually use JavaScriptSerializer().Serialize
instead of returning an object. The response from the web service will be double JSON encoded.
You are right! There are a lot of a close questions. Look at here Can I return JSON from an .asmx Web Service if the ContentType is not JSON? and Can't get jQuery Ajax to parse JSON webservice result and you will (I hope) find the answer.
UPDATED: Sorry, but you have a small error somewhere what you didn't posted. To close the problem I created a small project with an old version of Visual Studio (VS2008) which has practically exactly your code and which work. I placed it on http://www.ok-soft-gmbh.com/jQuery/WSMember.zip. You can download it, compile and verify that it works. Then you can compare your code with my and find your error.
Best regards
How to return JSON from ASP.NET .asmx?
Do you have .NET 3.5 or greater installed?
ScriptServiceAttribute is in .NET 3.5 and 4.0.
Also, clear your ASP.NET temp files, the dynamic proxy could be cached.
How to return JSON from a 2.0 asmx web service
It's no problem to return JSON from ASMX services in ASP.NET 2.0. You just need the ASP.NET AJAX Extensions installed.
Do be sure to add the [ScriptService] decoration to your web service. That's what instructs the server side portion of the ASP.NET AJAX framework to return JSON for a properly formed request.
Also, you'll need to drop the ".d" from "msg.d" in my example, if you're using it with 2.0. The ".d" is a security feature that came with 3.5.
get JSON from ASP.NET web service ASMX file
If you want to return JSON from your method you will need to use the ScriptMethod attribute.
Structure your method like this, notice the [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
attribute.
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string MyMethod()
{
}
At the moment, this method is returning a string
, which can be a JSON
structured string. However, you may be better to return an object, which can be parsed as JSON
. List<string>
as well as Class's with standard data-types, like integers
, strings
etc are great for this. You can then return just that object. the ScriptMethod
takes care of transforming it into JSON
.
For example:
The Class you want to return:
public class MyJson
{
public int ID;
public List<string> SomeList;
public string SomeText;
}
And your method to return a populated MyJson
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public MyJson MyMethod()
{
MyJson m = new MyJson();
m.ID = 1;
m.SomeText = "Hello World!";
m.SomeList = new List<string>();
m.SomeList.Add("Foo");
m.SomeList.Add("Bar");
return m;
}
The return JSON
will be structured just like the class. The property names will be used too, and your List<string>
will become an array
Call this using AJAX. JQuery in this case:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "/YourPage.aspx/MyMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// content will be in here... I.E
var id = msg.d.ID;
var st = msg.d.SomeText;
var sl = msg.d.SomeList;
var i = sl.length;
var firstSlItem = sl[0];
}
});
});
Related Topics
Run Async Method Regularly with Specified Interval
How to Get Windows Display Settings
Best Way to Specify Whitespace in a String.Split Operation
The Name 'Controlname' Does Not Exist in the Current Context
Send a File via Http Post with C#
Copy File(S) from One Project to Another Using Post Build Event...Vs2010
ASP.NET MVC: How to Display a Byte Array Image from Model
Split a String with Delimiters But Keep the Delimiters in the Result in C#
JSON.Net Throws Stackoverflowexception When Using [JSONconvert()]
Cast List<T> to List<Interface>
Making a Simple Ajax Call to Controller in ASP.NET MVC
How to Properly Exit a C# Application
How to Write a Backslash (\) in a String
How to Make Something That Catches All 'Unhandled' Exceptions in a Winforms Application
Mod of Negative Number Is Melting My Brain
Draw Semi Transparent Overlay Image All Over the Windows Form Having Some Controls