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
Similar 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 instead.
If you're replying to an existing comment, please use the threading feature. To do this, click the "Reply to this" 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.
you can use List to implement this.
let me know i u need the code..
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.
This does not work with the XMLDOM object. I can get this to work using the old MS behaviors (HTC). But stringify does not work on a XMLDOM object. Is there another way to pass a XMLDOM as an XMLDOM object?
Great post. Really informative. I’m a beginner. It’s really useful for me. Great site!
How does the web service handle the dto object?
The “ScriptService” functionality handles that automatically. It’s similar to MVC’s model binding approach.
In my post I explain how to pass generic unknown types.
It’s a very nice artical.
Keep it up…..
I want to return a class object from aspnet like this
[WebMethod]
public static Person AddPerson(Person NewPerson)
{
NewPerson.Add();
return NewPerson;
}
but when i try to use this code, the jquery ajax return a error “200″….
i need it to get the PersonID propertie in NewPerson object… how i can do it?
Are you using a Page Method or a separate ASMX ScriptService? If it’s a ScriptService, the AddPerson method should not be static.
Thank you Dave, for this excellent update. I just rewrote my code! Never too late to learn.
Is it possible to pass an array of objects of different object types in one JSON request?
Something like an Object[] or Dictionary?
I believe that’s possible, but I’m not sure I’d recommend it. What’s the problem you want to solve with this?
Dave: Say I have two objects on the server: A Father object and a Son object. *The relationship in my database is 1-to-many. The Son object has an id ref to the Father object primary key.
I’d like to pass a call to a WebMethod in one JSON request to simply populate the database for the Father and Son tables. Something like {“oFather”:{“oSon_1″:{…},”oSon_2″:{…}}}
Is this possible to do in one call to the web service? The tough part is that there could be a variable or unknown number of Son objects for any given call to the server WebMethod.
Hope that wasn’t too confusing. Thx.
You can do that. Hers’s an example of that kind of nesting:
On the client-side, collections like List and arrays correspond to a JavaScript array. So, your object would look something like:
There are a variety of ways to achieve the right structure on the client-side. Just remember that server-side object properties correspond to client-side keys, and server-side collections correspond to client-side arrays (potentially arrays of objects themselves).
One great way to figure out more complex structures is to create the data structure on the server-side and return it from a service method, then inspect it in Firebug. Looking at the JSON that the server returns for a given structure, you’ll also understand what the server expects to see if that structure is an input parameter.
Dave,
Excellent info on jQuery with .Net! I’ve been on your site for the past few days learning the ins and outs, though I still have a problem yet to resolve with a web service method (.asmx file) to which I’m trying to pass an array of objects. I keep getting an internal server error message back. It seems the .Net JSON serializer can’t render this data
{ "items":[ {"Id":"efab41de-cdb6-4362-860d-8924f841c45d","Ordinal":0,"Result":""}, {"Id":"dfab41de-cdb6-4362-860d-8924f841c45d","Ordinal":1,"Result":""}, {"Id":"tfab41de-cdb6-4362-860d-8924f841c45d","Ordinal":2,"Result":""} ] }into this object (VB):
_ Public Class Sortable Private _Id As Guid Public Property Id() As Guid Get Return _Id End Get Set(ByVal value As Guid) _Id = value End Set End Property Private _Ordinal As Int32 Public Property Ordinal() As Int32 Get Return _Ordinal End Get Set(ByVal value As Int32) _Ordinal = value End Set End Property Private _Result As String Public Property Result() As String Get Return _Result End Get Set(ByVal value As String) _Result = value End Set End Property Sub New(ByVal i As Guid, ByVal o As Int32) Me.Id = i Me.Ordinal = o End Sub Sub New(ByVal i As Guid, ByVal o As Int32, ByVal r As String) Me.New(i, o) Me.Result = r End Sub End ClassThe Sortable object is defined within the Web Service class. Right now the method looks like this (VB):
_ Public Function SetItemOrder(ByVal items As List(Of Sortable)) _ As List(Of Sortable) Dim results As New List(Of Sortable) For Each item As Sortable In items ' do something that updates the item.Result property If item.Result "success" Then results.Add(item) End If Next If results.Count = 0 Then Dim r As New Sortable(Guid.Empty, 0) r.Result = "success" results.Add(r) End If Return results End FunctionI’ve tried passing items as a ParamArray, as a Sortable() array, etc. I’ve tried changing the Sortable object Id from guid to string. I know the method getting accessed. Can you help?
That looks correct to me, and is within JavaScriptSerializer’s capabilities. What specific error is being returned from the server?
I used Chrome’s developer tools to figure out that the method was failing because apparently the JavaScriptSerializer has issues parsing Guids. I had to change the type of the Id property of my Sortable object from a Guid to a String. Then the object serialized ok. I added an Id variable of type Guid to the method and converted the Id string back to a Guid for processing. Have you heard of any issues with sending JSON objects containing Guids to a web service or is there a specific way to type a JSON object property as Guid?
I ran a quick test with this service:
Calling it like this:
And it appeared to work okay:
There must be something else going on in your situation.
Turns out it was bad test data. I realized yesterday that .Net didn’t like my hand-coded Guids which I made by changing the first digit of an existing Guid from my db to create a “new” Guid for testing. I naively figured as long as the value was “unique”, then it wouldn’t matter, but .Net didn’t like it when I passed the “new” Guid into New Guid(myGuid). I generated another real Guid for my test data and it worked fine. I changed my Sortable Id back to Guid, passed in the real Guids and that worked, too. I didn’t know Guids had to have a particular pattern of characters.
Thank you for taking the time to help!
Thanks a lot. Lucid explanation.
If the user already uses ASP.NET AJAX controls, he can use the existing serialize/deserialize methods, without the need to reference json2.js:
var DTO = { ‘NewPerson’: NewPerson };
var strDTO = Sys.Serialization.JavaScriptSerializer.serialize(DTO);
–>i.e.:
{“d”:{“__type”:”jQueryTest.Person”,”FirstName”:”Peter”,”LastName”:”Loveless”,”Address”:”Skipping”,”City”:”Hollywood”,”State”:”XYZ”,”Zip”:”88888″}}
If you serialize a returned Person-Object from your Webservice, it only attaches a property called __type, which contains the Name of the returned type.
back to object:
var _dto = Sys.Serialization.JavaScriptSerializer.deserialize(dtoStr);
Very good job !!!
Dave, great post! Part two would have to include the addition of client side validation.
Thanks for this most useful blog .. finally someone that knows what they are talking about. I was going round the bend trying to figure this out.
I’ve walked through the demo without any hassles. When I try to implement the same kind of logic in my existing web service. I keep getting this error: Invalid web service call, missing value for parameter.
That’s usually due to a mismatch between your DTO’s top level key and the name of the parameter that your service method expects. Make sure that in this step:
The key name (NewPerson in this case) matches the name of your method parameter, with case-sensitive accuracy.
If that doesn’t help, show me your service method’s signature and your client-side DTO/$.ajax() code.
Ah never mind figured it out… silly mistake. Parameter variable name wasn’t matching because I had a typo. Doh!