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