This topic could have been more familiar and kind of outdated to many. But I think it is good to see how we use JavaScriptSerializer in our applications to work with entities without a language or technology barriers.
Suppose we have an entity ( class with set of properties ) class and we use it as data objects in our application. And now we need it to be serialize into JavaScript objects to be used in Ajax. We can easily follow the below way,
1. Create an entity class
2. And your asmx (web service) file has the below web method.
Here we use Serialize method to convert the object into de-serializable string and your JavaScript function can handle the response as follows,
The JSON result is the list of objects that you pass from your service. In this way, we can deal with larger objects but we need to concern about the JSON limitations. We will discuss about how we can overcome JSON limitations in the future posts. Until that, happy coding.. :)
Suppose we have an entity ( class with set of properties ) class and we use it as data objects in our application. And now we need it to be serialize into JavaScript objects to be used in Ajax. We can easily follow the below way,
1. Create an entity class
public class personEntity
{
public int? idEntity{ get; set; }
public int nameEntity{ get; set; }
}
2. And your asmx (web service) file has the below web method.
[WebMethod]
public string GetEntityList ()
{
return new JavaScriptSerializer().Serialize(new PersonBLL().GetPersonList());
}
Here we use Serialize method to convert the object into de-serializable string and your JavaScript function can handle the response as follows,
function GetPersonList() {
$.ajax({
type: "POST",
url: "ServiceURL/GetPersonList",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var ret = JSON.parse(msg.d);
$.each(ret, function (i, item) {
alert(item.idEntity);
alert(item.nameEntity);
});
},
error: function (err) {
alert(err.responseText);
}
});
}
The JSON result is the list of objects that you pass from your service. In this way, we can deal with larger objects but we need to concern about the JSON limitations. We will discuss about how we can overcome JSON limitations in the future posts. Until that, happy coding.. :)
No comments:
Post a Comment