Using complex types to make calling services less… complex
AJAX, ASP.NET, JavaScript, jQuery By Dave Ward on April 7th, 2009So 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
Possibly related posts
What do you think? Your comments are welcome.
I appreciate all of your comments, questions, and other feedback, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to an existing comment, please use the threading feature. To do this, click the "Reply to this comment" link underneath the comment you're replying to.
5 Mentions Elsewhere
- Using complex types to make calling services less… complex | Encosia - DotNetBurner
- Dev 4 Web » JQuery and ajax call to ASP.Net using object
- DotNetShoutout
- Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-04-09
- Getting to Grips with Form Submission using jQuery .ajax() - My Tech World


@Dave – As much as I agree with you on using objects to pass data, I’d also say this needs to be taken one step further and wrapped into a reusable component that handles the JSON encoding (and unwrapping of WCF/ASMX result data) transparently.
As you probably know WCF objects return wrapped objects and you’re still stuck with the problem of the JSON evaluator not knowing what to do with a .NET returned date. There’s also the nasty issue of error handling with $.ajax() method if a transport level error occurs.You don’t want to have to think about these implementation details every time you make a service call.
I a serviceProxy class a while back that wraps the .ajax() call and handles these issues. Some of your readers might find this useful:
http://www.west-wind.com/weblog/posts/324917.aspx
BTW, love the trick of using the ID to create the object on the fly – learn something new every day!
Great post!!!
Thanks a lot!!
I love this blog, always very informative posts.
Could you help me out how to handle DateTimes with Webservices?
i always have issues with it..
Regards
Dave
I generally try to pass DateTime values around as strings, to avoid the messy client-side issues that no Date() literal leaves us with. As much a kludge as it sounds like, it works great.
If I return a ToShortDateString() or ToLongDateString(), that’s almost always what I actually need on the client side. If I do end up needing proper JavaScript Dates, either form is still useful.
For example, today these all create equivalent Date objects (though the time portion is obviously different on the last one):
Similarly, you can pass any reasonable Date/Time string into an ASP.NET AJAX “ScriptService” and it will parse a DateTime if dictated by the input type(s).
Thanks a lot !
I am using similar solution but your post is perfect !
Hi Dave,
This is exactly what I was looking for. I was asking you for the same thing in my previous mails. Really excellent post!
You have mentioned that:
“An underutilized feature of ASP.NET AJAX “ScriptService” methods is that they can accept complex types as parameters and parse those parameters from JSON.”
Our client wants us to use only jQuery for AJAX and nothing else. So what should be the case now?
Great post Dave! I had been wondering how to use complex types while doing ajax calls with jQuery.
Great post! I’m refactoring my code right now.
By the way, there seems to be a typo on the last code block – you meant
var Person = {};
right?
You’re right. Thanks for pointing that out.
Why do you keep using JSON.stringify(…)? Try this:
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,
dataType: “json”
});
You don’t have to pass strings in to data, jQuery also takes ojbects and anonymous objects (i.e { field: value } )
It’s required for calling ASP.NET AJAX services. Passing jQuery the object directly will result in it serializing it as ?key=value&key=value instead of passing the JSON along to the server.
Passing that to an ASP.NET AJAX “ScriptService” will throw an Invalid JSON Primitive error on the server side.
Nice idea, but is there a way to get Visual Studio to show me some Intellisense about the objects?
Just like in Ajax.Net (the automatic proxy), but for jQuery would be perfect (I don’t want to use the whole bunch of javascript files just for ajax)
@Krishna: the ASP.NET AJAX thing Dave is referring to is on the server-side, so no need to take the dependency on the client-side.
@Dave: the use of jQuery selection may be a little overkill here. Putting your fields in a nice form tag would (besides helping the no-JavaScript degradation story) enable you to just enumerate its fields to build the object. Actually, it would be interesting to see how much JavaScript code you’d have to write for a completely no-dependency implementation of the same scenario.
I only used the jQuery selector because I was already using jQuery to call the service. Since it wasn’t an extra dependency, it made sense to go with the more concise code in that loop.
You could use getElementsByTagName() to do the same. Something like:
jQuery also has a plugin called $.toJSON(NewPerson)
The reason I went with json2.js is because the browsers are copying its API for their native functionality. JSON.stringify() will be the standard.
Great post! In response to the commented question about intellisense on the Person object, you can do something like the following:
function Person(firstName, lastName, address, city, state, zip) {
this.FirstName = firstName;
this.LastName = lastName;
this.Address = address;
this.City = city;
this.State = state;
this.Zip = zip;
}
function GetPerson() {
var NewPerson = new Person(
$(“#FirstName”).val(),
$(“#LastName”).val(),
$(“#Address”).val(),
$(“#City”).val(),
$(“#State”).val(),
$(“#Zip”).val()
);
return NewPerson;
}
As usual.. too good.Thanks for such nice and informative articles.Keep going!!
Hi Dave,
Very interesting, I adopt it right away.
A suggestion to reduce the script:
// Create the Employee data transfer object (DTO)
var EmployeeDTO = JSON.stringify({ ‘NewPerson’ : {
FirstName: $(“#FirstName”).val(),
LastName: $(“#LastName”).val(),
Address: $(“#Address”).val(),
City: $(“#City”).val(),
State: $(“#State”).val(),
Zip: $(“#Zip”).val() }
});
$.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8″,
url: “PersonService.asmx/AddPerson”,
data: NewEmployeeDTO,
dataType: “json”
});
Nice post!
We can also do some filters on the input elements via something like $(“:input”).filter(“[name^='item']“)
Cool!
Hi Dave,
Another excellent stuff…!!
I have a question, in my case JSON.stringify() doesn’t works however, JSON.encode() does. Don’t know whats the problem. Is it fine if I use JSON.encode()?
Dave,
This article is very timely. I was working with this exact idea this week. I just about came up with the same thing and I used Rick Strahl’s wrapper.
The other thing I did for dates on the server side is to use JSON.Net to serailze an object with a date like this
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
[WebMethod()]
public static string GetCustomersJSON()
{
List customers = LoadCustomers();
IsoDateTimeConverter idtc = new IsoDateTimeConverter();
idtc.DateTimeFormat = “MM/dd/yyyy”;
return JavaScriptConvert.SerializeObject(customers, idtc);
}
JSON.Net from James Newton-King
http://www.codeplex.com/Json
I think this is the most used JSON library but I need to see what .Net has. When I googled JSON and ASP.Net that is what came up.
One side affect of exploring JQuery is that it exposes how much bloat Microsoft has in their tools as well as how bad IE fails in implementing web standards.
Thanks for the great articles!
Paul
I wrote a some jQuery code to make the asp.net web service javascript use jquery ajax method.
Now you can call the function as it is in c# code.
Namespace.ClassName.AddPerson(FirstName, LastName, Address, City, State, Zip)
http://thorsteinsson.is/projects/jquery-webservices/
Great post – my only comment would be that since you are relying on id’s then you have to be careful not to put the textbox’s in a panel or anything like that as I suspect the generated client Id’s may cause issues.
Very well done. Thank you for writing this.
great stuff! thanks for sharing!
Nice post…
Thanks for this post. Very useful. I’ve implemented it straightaway. It works fine but something (slightly unrelated but interesting) I noticed is that if I move the webpage (which is calling the webservice) into a subfolder the jquery ajax function stops working.
It looks like the webpage (.aspx) and the webservice (*.asmx) have to be in the same folder.
In your example, the url of your ajax call is PersonService.asmx/AddPerson so if you call it from a subfolder you would expect this to work instead: ../PersonService.asmx/AddPerson but it doesn’t.
I did some more tests and I didn’t find a way to call the webservice from a webpage in a subfolder. Any ideas why would that be?
I can vouch that it *should* work. In real projects, I generally keep my services in separate subfolders.
How is it failing? 404? 403?
Try using a url that starts with the root path, so that if you had a structure like so:
/Project/People/Pages/AddPerson.aspx
/Project/People/PeopleServices.asmx
the ajax url would be “/Project/PeopleServices.asmx/AddPerson”, I know this works from personal experience
Nice article, i tried it and its working fine and gr8.I have a question here.How can i pass a collection of objects from javascript,and accept it as a generic list in the server side.Any idea??
A JavaScript array will translate to a collection on the server-side. If you were to do something like this:
That would construct an array of Person objects on the client-side. If it were stringified and sent as the data parameter, that would work as expected with a method accepting a List parameter named People.
Thank you very much Dave,for your quick response.Thanks for your time.
Thanks Dave,
This is what I was looking to achieve because I needed to do a batch update.
This seems to be the way for me to do it. I was trying to us an asp GridView but it was dog slow.
This site has been invaluable for learning how to handle JSON with jQuery and ASP.
Very useful post; thank you.
“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!”
Yup, so long as you aren’t a dummy like me and remember in your class to:-
a) include (or allow) a parameterless constructor;
b) ensure the properties’ setters are public.
Doh!
I’m so used to producing DTOs that go from server to client only, that I make the setters internal (or private) by default.
ASP.Net Ajax also has these features as explain in my blog http://www.rajeeshcv.com/2008/10/aspnet-ajax-passing-json-object-from-client-to-server/
Dave, you are a champ. I spent 2 days tryinig to pass back a compex object from jquery to asp.net. I follofwed your example and it worked. Keep up the good work. We need more people like you.
I’m trying to pass a 2D array to y web method, but I’m not sure how to consume it. Using JSON.stringify, I get…
'{"numbers":[[1,1],[2,3]]}'and I tried to consume it with…
but i get a “is not supported for deserialization of an array” error.
Which data types can I use?
Use uint[][] instead, and that request parameter will work.
Great article as it shows clarity of mind…
Dave,
I’ve been using the methods described in this article and I’ve gotten to the point where my objects to serialize are a little more complex and I’m running into errors trying to pass them between client and server. The object I want to serialize contains a List, where CustomObject contains a couple of primitive types.
Here is a link to a simplified demonstration of the problem
This was my initial attempt at jsonifying my client object. It resulted in the error
“The value “System.Collections.Generic.Dictionary`2[System.String,System.Object]” is not of type “CustomObject” and cannot be used in this generic collection. Parameter name: value”
Next, I tried using System.Web.Script.Serialization.JavaScriptSerializer to serialize an instance of my class just to see how the that serializer would do it. I noticed that the JavaScriptSerializer included a “__type” attribute and I copied that value into my client code as an attribute of the client-side object.
Here’s the same project modified to use the “__type” attribute.
This seems to get me closer to my goal, but now I get the error
“Operation is not valid due to the current state of the object.”
I’d appreciate any advice you can offer me on properly jsonifying this data structure.
That first paragraph should end: “The object I want to serialize contains a List<CustomObject>, where CustomObject contains a couple of primitive types.”
If you can use a List instead of your CustomObjectList, it will work. Worst case, use a simple structure like that as a DTO and map that to your CustomObjectList in the service method.
Thanks very much Dave. I appreciate your advice.
Hi all,
I am using Linq to sql and DTO approach with WCF what i am able to achieve is direct object property transfer but what if i want to insert all the other dependent objects within the same call.
For example
If my UserTable is related with EmployeeTable and i want to insert data in both the tables do i have to pass both objects from jQuery UI or i can do something like
UserTable.Employee.FirstName = $(‘#tbFirstName’).val();
and pass the user object to WCF call and in the WCF call what will have i to write to submit all the changes in the datacontext.My guess would be InsertAllOnSubmit.
If this is not the correct approach then what could be the best approach.
Thanks
I think it may be too oblivious. This method needs to be static, right?
[WebMethod]
public static void AddPerson(Person NewPerson)
It would need to be static if it were a page method. In this example, I’m using an ASMX service method instead of a page method, so the static modifier isn’t necessary.
Thanks for the reply. I really enjoy your articles.
It’s really a great post. Thanks for your valuable post.
Great post, It changed my application architecture,
Dave Is there anything like this in Java Web Services?
I’m not familiar enough with Java to know specifically what its counterpart of this is, but there should definitely be one.