Note: This post is part of a long-running series of posts covering the union of jQuery and ASP.NET: jQuery for the ASP.NET Developer.

Topics in this series range all the way from using jQuery to enhance UpdatePanels to using jQuery up to completely manage rendering and interaction in the browser with ASP.NET only acting as a backend API. If the post you're viewing now is something that interests you, be sure to check out the rest of the posts in this series.

So far, my examples of using jQuery to interact with ASP.NET AJAX services have avoided passing complex data to the server during the request. This has been intentional, because I didn’t want to over-complicate the examples.

For primarily read-only scenarios, like the RSS reader examples, passing just a few simple values to the service is often all you need. However, this scalar approach quickly becomes untenable when making real-world service calls.

In this post, I’m going to show you how passing complex types to the server helps alleviate complexity, how json2.js and a data transfer object (DTO) facilitates this, and how to use jQuery to very easily build the DTO.


Setting the stage

Let’s say that we want to improve the performance of a data entry application used to add Person records to a database. The original version was developed quickly using an UpdatePanel, but performs poorly. Not wanting the Person-data-entry-department to spend more time waiting than they do typing, we must find a way to improve the application’s performance.

Having done some research, we might decide that replacing the UpdatePanel with jQuery and a web service would be a great way to speed things up.

A foundation and a facade

The properties of the existing Person class could be as simple as this:

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Address { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public string Zip { get; set; }
 
  public void Add()
  {
    // Magic happens here.
  }
}

The original entry form probably used TextBox controls, but that will no longer be necessary. Regular HTML input elements carry less overhead and ensure that we don’t have to worry about ClientID issues:

<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" />
 
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" />
 
<label for="Address">Address:</label>
<input type="text" id="Address" />
 
<label for="City">City:</label>
<input type="text" id="City" />
 
<label for="State">State:</label>
<input type="text" id="State" />
 
<label for="Zip">Zip:</label>
<input type="text" id="Zip" />
 
<input type="button" id="Save" value="Save" />

Note that the input elements have IDs matching the corresponding Person property. This will help us implement an improvement to our client-side code later on.

One way not to do it

Now that we’ve had a look at the front and back ends, it’s time to connect them together with a web service. One unfortunate anti-pattern that often emerges in this situation is a service method with too many parameters:

[WebMethod]
public void AddPerson(string FirstName, string LastName, 
                      string Address, string City,
                      string State, string Zip)
{
  Person newPerson = new Person();
 
  newPerson.FirstName = FirstName;
  newPerson.LastName = LastName;
  newPerson.Address = Address;
  newPerson.City = City;
  newPerson.State = State;
  newPerson.Zip = Zip;
 
  newPerson.Add();
}

Not only do we have to manually keep that method’s parameter list in sync with the Person class, but we also have to maintain the pointless object initialization code.

Calling the service on the client-side is just as messy too:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'FirstName':'" + $("#FirstName").val() + "', "
       + "'LastName':'" + $("#LastName").val() + "',"
       + "'Address':'" + $("#Address").val() + "',"
       + "'City':'" + $("#City").val() + "',"
       + "'State':'" + $("#State").val() + "',"
       + "'Zip':'" + $("#Zip").val() + "'}",
  dataType: "json"
});

As ugly as it is, that will work and be much faster than anything we could possibly implement in an UpdatePanel. It would also be a nightmare to maintain.

Let’s continue improving this until it’s something we can be proud of.

Things can only get better

A good first improvement is to refactor the web service to get rid of the parameter list and redundant object initialization.

Most examples (including my own) never go beyond passing a string, integer, or maybe an array, but that only scratches the surface of what’s possible. An underutilized feature of ASP.NET AJAX “ScriptService” methods is that they can accept complex types as parameters and parse those parameters from JSON.

Leveraging this, we can dramatically simplify the web service:

[WebMethod]
public void AddPerson(Person NewPerson)
{
  NewPerson.Add();
}

Unfortunately, calling this method on the client-side is just as messy as ever:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'NewPerson': {'FirstName':'" + $("#FirstName").val() + "',"
                     + "'LastName':'" + $("#LastName").val() + "',"
                     + "'Address':'" + $("#Address").val() + "',"
                     + "'City':'" + $("#City").val() + "',"
                     + "'State':'" + $("#State").val() + "',"
                     + "'Zip':'" + $("#Zip").val() + "'}}",
  dataType: "json"
});

That’s about the same as before. However, instead of sending a flat group of input field values, now we’re sending a JSON object corresponding to the Person class.

In other words, that declarative JSON data string is equivalent to this JavaScript:

var NewPerson = new Object();
 
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();

ASP.NET AJAX seamlessly translates the JSON string into a new instance of our Person class and passes that object into the service method. It works exactly as you’d expect, which is almost too good to be true!

Cleaning up the client-side

The best way to improve the client-side situation is to abandon our manual JSON serialization in the $.ajax() call. It works well enough for a couple parameters, but has devolved into a ball of mud as the parameter count increased.

Douglas Crockford’s json2.js contains a stringify function which is exactly what we need. Stringify() accepts a JSON object and returns the same type of string that we’re manually concatenating together right now.

Using json2.js, our previous client-side code can be refactored to this:

// Initialize the object, before adding data to it.
var NewPerson = new Object();
 
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
 
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: "{'NewPerson':" + JSON.stringify(NewPerson) + "}",
  dataType: "json"
});

It’s still a fair amount of code, but it’s much cleaner. If you dropped this in my lap and asked me to maintain it, we wouldn’t have a problem.

Using a data transfer object

Adding json2.js and its stringify functionality made our code significantly more readable, but we can do better. There’s still a bit of manual JSON string building in the $.ajax() call, which would be nice to avoid.

Since we already have JSON.stringify() at our disposal, we can build and stringify a JSON object to represent the entire request’s data instead of just the form data:

// Initialize the object, before adding data to it.
//  { } is declarative shorthand for new Object().
var NewPerson = { };
 
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
 
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
 
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: JSON.stringify(DTO),
  dataType: "json"
});

By creating a data transfer object (often referred to as a DTO), we’ve completely eliminated all manual JSON string building.

Even though it’s a small change, it feels quite a bit cleaner doesn’t it?

Bonus: jQuery makes everything better

Using the DTO makes sending the form data clean, but we’re still stuck with the unnecessary chore of maintaining the NewPerson initialization block. jQuery is perfectly suited to solving this problem:

// Initialize the object, before adding data to it.
//  { } is declarative shorthand for new Object().
var NewPerson = { };
 
// Iterate over all the text fields and build an
//  object with their values as named properties.
$(':text').each(function() {
  // Ex: NewPerson['FirstName'] = $('#FirstName').val();
  NewPerson[this.id] = this.value;
});
 
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
 
$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/AddPerson",
  data: JSON.stringify(DTO),
  dataType: "json"
});

Using jQuery.each() to iterate over the fields and build our client-side object is a nice improvement. Even in this simple example, it cuts down on the amount of JavaScript we have to write and maintain. In real-world scenarios where your objects have dozens of properties, this will save you a lot of time (and typos).

More important than saving a few keystrokes, we’ve got one less place to worry about updating if the Person class changes in the future. We can modify the Person class, update the entry form accordingly, and this will continue working.

Conclusion

We have solidly accomplished the goal of refactoring this until it’s something we can be proud of. There’s always room for improvement, but this will serve as a great start for writing robust, maintainable client-side service calls.

Death by a thousand dependencies: When I first started experimenting with this stringified DTO pattern, I was reluctant to take on the json2.js dependency. However, it’s tiny when minified, has no dependencies of its own, and is ideal for rolling into another combined script. Its dependable functionality is well worth a few kilobytes.

A great thing about committing to the JSON.stringify usage is that web browsers are beginning to natively support it. So, at some point in the future, you’ll actually be able to drop the json2.js dependency and this method will still work (faster).

DTOs: If your server-side situation is more complex than this example (and it probably is), don’t be afraid to use a throw-away DTO class as the service method parameter.

For example, our Person class could also have been a PersonDTO class, specifically intended to take these form submissions and merge them into a more complicated domain.

Source

jQuery DTO source download