Ajax using .Net and jQuery – Revised and improved with help from Json
I previously wrote a post outlining a simpler method of making asynchronous calls with jQuery. It turns out that in practice that method was exactly that – too simple. It works fine when you only need one value back, but if you need to work with something a little more complex then try out my new method that uses a JSON object. So the basic overview is as follows:
- create an object server-side on page load and add it to the DOM
- populate the object using javascript
- pass it back to a webservice using jquery’s ajax method and json
- use the new object serverside and pass it back
Ok, so lets get started by creating the object in your webservice:
{
public string Name { get; set; }
public string ContactNumber { get; set; }
public string Description { get; set; }
}
Then in your page load you can inject this object into the DOM:
Now you can use this object with javascript:
function AjaxMethodJSON(serviceFn, paramArray, successFn, errorFn) {
$.ajax({
type: "POST",
url: serviceFn,
contentType: "application/json; charset=utf-8",
data: "{‘clientobject’:" + JSON.stringify(paramArray) + "}",
dataType: "json",
success: successFn,
error: errorFn
})
;
…
$("#btnSubmit").click(function() {
objPerson.Name = $(‘#txtName’).val();
objPerson.ContactNumber = $(‘#txtContactNumber’).val();
objPerson.Description = $(‘#txtDescription’).val();
AjaxMethodJSON("/webservices/Webservice.asmx/UpdatePerson", objPerson, AjaxSuccessStep, AjaxFailed);
});
If you have been paying attention you may be thinking – stringify? The official explanation from json.org: If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation. So remember to add a reference to json2.js upstream from this code.
if (result != null) {
var obj = result.d;
objPerson = JSON.parse(obj);
//got the updated object back, now you can
//do some more stuff with it
}
}
There you go. This works very well when you are stepping through a wizard and updating a few fields with each step.
Developer by day, husband and dad by night and dreaming about sport inbetween.