I am new to JSON, and want to make simple JSON object using StringBuilder which would be queried by a jQuery Ajax call.
[WebMethod]
public static string GetmyJSON()
{
StringBuilder sb = new StringBuilder();
sb.Append("{firstname: \"Manas\",").Append("lastname : \"Tunga\"").Append("}");
return sb.ToString();
}
In my client-side code i have:
.ajax({
type: "POST",
url: "simplePage.aspx/GetmyJSON",
data: "{}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
alert(data.d.firstname);
} // end of sucess
}); // End of ajax
But my alert message shows 'undefined' instead of 'Manas'. Is it possible to return a JSON object using StringBuilder?
Never do that. Never build JSON manually. Always use JSON serializers. Or in your case you don't even need to do that because the ASP.NET webmethod runtime will take care. All you have to do is focus on your business requirements and don't worry about plumbing.
So for example start by defining a model that will represent your data:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
and then have your web method return this model leaving all serialization concerns to the framework:
[WebMethod]
public static Person GetPerson()
{
Person p = new Person();
p.FirstName = "Manas";
p.LastName = "Tunga";
return p;
}
And now simply consume this method from the client:
$.ajax({
type: 'POST',
url: 'simplePage.aspx/GetPerson',
data: '{ }',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.d.FirstName);
alert(data.d.LastName);
}
});
No need to worry about JSON, string builders, ...
And you could also pass complex arguments to your web method if you needed to:
public class Foo
{
public string Bar { get; set; }
}
and then:
[WebMethod]
public static Person GetPerson(Foo foo)
{
...
}
and finally:
$.ajax({
type: 'POST',
url: 'simplePage.aspx/GetPerson',
data: JSON.stringify({ foo: { bar: 'baz' } }),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.d.FirstName);
alert(data.d.LastName);
}
});
The JSON.stringify
method shown here is natively built into modern browsers. If you need to support legacy browsers you could include the json2.js script to your page.
var lstMes = new List<Person>();
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(lstMes);
return sJSON;
dont forget to add reference to :
System.Web.Extensions.dll !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With