As websites become more and more interactive the need frequently arises to send data back and forth between web clients and servers using Ajax. ASP.NET combined with jQuery makes this process simple to implement for web developers.
The server side
Now let’s write our method. All we need to do is create a standard ASP.NET MVC controller method which takes a single parameter of the Person type, like so.
As mentioned, I’m returning a Boolean value indicating whether the person object was successfully received.
That’s all we need to do on the server side. Let’s writ the client-side code.
The client side
The first thing we’ll do is use jQuery to write the Ajax call.
Here we’re invoking the ubiquitous “ajax” method, passing it an object containing all the information it needs to get the job done in the form of field values. Let’s take a brief look at each one.
The url field contains the dynamically-calculated address of our target method.
The type field indicates the type of HTTP request we wish to send. In this case it is a POST request.
Here we are specifying that the data is of the JSON format. This is important as it provides the server with the knowledge it needs to be able to deserialise our data into a POCO object.
The data field contains the actual data that we want to send in the POST request. There are two things of note here. The first is that we have assigned our “tommy” object to a field named “person” in a new anonymous object. Why is this? Well, the JSON object that we send to the server needs to correspond to the signature of the method that will receive the request. As our method looks like this:
We need to send it an object that looks like this:
This function executes if the request succeeds. While in this case I’ve used an anonymous function, I could also have externalised this method and set “success” to a function pointer instead.
This is all the server side code we need. Let’s fire up our website and run the code to see what happens.
Making the call