Using complex types to make calling services less… complex
AJAX, ASP.NET, JavaScript, jQuery By Dave Ward. Updated June 6, 2009Note: 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
Similar posts
What do you think?
I appreciate all of your comments, 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 another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.
8 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
- PageMethods usando JQuery – Parte 2 « Diego Doná | Designer, Developer
- vb.net asmx WebService to accept JSON in HTTP-POST using Android - Applerr.com All about Apple Products - Applerr.com All about Apple Products
- Sending JSON to an ASMX Web Service « Personal Portal



@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.
Hi Dave,
Awesome post! I found that I can pass in a JavaScript Array to my function and serialize it without adding another dependency (JSON2) by using
Sys.Serialization.JavaScriptSerializer.serialize()
However, I’m new and need cross browser functionality so… what are your thoughts on this serializer? Also, I plan on changing this to hit a WCF web service.
Here’s my JavaScript function:
Here is my VB.NET web service method:
Thanks
I tested that stringify works in IE8, FF, and Safari without JSON2.js so I’m going to use that :)
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!
Dave,
Since reading this article, I use this method in almost all my projects. Now, I’ve been given a requirement that nearly fits the scope of this method, but not quite. I need to provide a link (button, image, div, whatever) that when clicked will download a .csv file. This .csv file needs to be created dynamically based on a javascript object known to the browser. I can handle all the Context.Response issues (i.e. .ContentType, .Write(“my csv data here”)) in a web service, but my trouble comes in calling the web service from the client. How do I pass a javascript object to the web service when I don’t want an ajax-type post?
Given the web service:
…how do I call that from the client so that the response is a full-fledged regular old non-ajax response that gets treated as a downloadable file by the browser?
If you can fit the parameters needed to generate the CSV on the QueryString, I would suggest using an HttpHandler to generate the file based on QueryString parameters and point the browser at that URL. As long as the HttpHandler sets the content-disposition of its response to attachment, the browser will pop up a “save” dialog instead of navigating. That tends to work a lot better than AJAX-esque trickery.
You can either load up an anchor element’s href with the QueryString’d up URL if you know the parameters before the user requests the file, or dynamically generate the URL with parameters and assign it to window.location to trigger the download. The latter method is more flexible, but may raise the security bar in IE.
Thanks Dave. Given your response, I realize this is an inappropriate forum for the question. I appreciate your expertise and kind advice.
Thanks Dave.
My problem is a bit more complex though. What would you do in the following scenario:
The NewPerson Class will also be changed to : NewPerson.Other.FirstName etc.
I tried this and it throws an error saying “Other” is null or not an object. Any ideas what to do?
I appreciate any help. Thanks.
Nevermind. I think i figured it out.
You can simplify that a bit, like this:
G8 post you make my day!
Very Great Post. Thanks Dave!
Hi all, this looks really good but i cannot make it to work correctly. can someone please take a look a this and tell me if there is something wrong, thanks so much.
this is my class Product.cs
then i have the WebService which should be really straight
The Javascript
and finally the html
Product ID: Name: Price: Peso: Modelo: Condition:Thanks in advance
Sorry about the html anyway i make sure that the input text id’s match my class Product, no doubt in that.
Are you getting a JavaScript error? If you inspect the request in Firebug, do you see the correct JSON being sent to the server?
Hey Dave thanks for your response, anyway i start the same thing in my house and it works, thanks a lot for your help, I’m been using UpdatePanel so far, maybe because i work in a intranet environment so the it does not hurt to much, but it is always worth it try better ways.
Thanks again, keep up the good work!!!!
Great article.
Just in case anyone gets the error “operation is not valid due to the current state of the object”, when testing localhost using Visual Studio’s built-in web server, try it using IIS instead. Without any change in code, everything worked perfectly. I even tried adding the GenerateScriptType attribute to the webservice class according to http://stackoverflow.com/questions/3819071/asp-net-scriptservice-deserialization-problem-with-derived-types but that didn’t work.
Just to follow up my previous comment:
After adding the GenerateScriptType attribute as referenced in the link attribute and the json property “__type” with the correct .NET type including namespace, which was in my case the project name, I now get no errors while debugging using Visual Studio 2010′s built-in web server. I was missing the namespace.
Just what I was looking for, awesome.
thx for share
Hi.
Special thanks for your pretty posts :)
Can we use jQuery serializer API and mapping serialized data to C# object?
Excellent article!! I knew all of this was possible but was wrestling with the syntax for about an hour. Works like a charm. Thanks!!
Hi Dave,
I’m a complete newbie for all the Json theme –
The situation I’m facing is that I need to receive data from a client. The client is sending the data as JArray of Json objects. The structure of the json objects is not strict (and I don’t want it to be). On my server I’ve published an ASMX web service with a web method holding single string parameter. I expected to get the Json data as one long string and parse it internally (using Json.NET). The things get complicated as my client doesn’t have any knowledge whatsoever in ASMX web services nor in .net.
Reading your example, I assume he should take the complete array of Json objects and use the ‘stringify’ on it as a whole, something like this:
data: JSON.stringify([{"..."},{"..."}])
Am I right here?
another question – what dataType should he use? because now it is not “json” but rather a simple “string”
Thanks in advanced,
Alon
Since ASP.NET is going to be attempting to deserialize the input parameter from JSON to a server-side type no matter what, it’s best to find a .NET type that matches what you want to send.
If you want to maintain a relatively ad-hoc structure, you could use something like a Dictionary and then your client could pass in any number of arbitrary data like
{"key1":"foo","key2":true,"key3":42}and you could access it on the server-side by known key name or by iterating through the keys.Hi Dave, thanks for your quick reply.
Things are starting to be clearer :)
So, reading the other article, I assume both ways (using an object or strinigify) can be valid working way (especially as I need the flexibility, cannot change the client side…).
One further question though (In case I will use the object way) –
The data from client will have this Json array form: [{"Rec":{"F1":123,"F2":456,...}},{"Rec":{"F1":789,"F2":101,...}}]
So I thought of crating a .Net “Rec” object and publish a method expecting array of Rec:
[WebMethod()]
public void JsonObjArrReport(Rec[] RecsToSave)
Am I right here?
Thanks again,
Alon
Yes, that should work. You can even use a
List<Rec>if you want and it will still work automatically.The thing to keep in mind is that ASP.NET will be attempting to deserialize the input value regardless. So, if you want to accept a JSON string and handle the deserialization yourself, your client will still need to add an extra layer of JSON serialization on their end, complete with escaped double quotes, for that to work. For example:
It turns into a mess pretty quickly when you work against this particular aspect of the framework. If you do go the manual deserialization route, you’d probably be better served by an HttpHandler instead.
OK, thank you very much for the support and for a great set of articles!!
Dave, if I remember correctly, Dictionary isn’t serializable.
JavaScriptSerializer handles Dictionary okay (even with a dynamic value type). You can run this in LINQPad for a quick demo:
@Dave.. Thanks for such a informatic session…
I was redirected by you from your previous link..
http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/#comment-54270
I am .net developer and now our company need to make iPhone web app.. we have our wcf REST service and all operation contract’s body style is wrapped..
I am sorry to ask this question here.. But I am very new for java and jQuery…
I am developing iPhone web app in MONO Develop C#..
Where can i find JSON.stringify(),
In C#, you can use JavaScriptSerializer to build JSON strings.
Thanks for reply..
I can use JavaScriptSerializer to build JSON string, but as i mentioned we have WCF service which have bodystyle = “Wrapped” so, what ever json i am sending is need to wrapped..
{“person”:{“Name”:”testname”,”Phone”:”00000000″}
how can i add automatic parameter name before starting of json string.
Thanks
You can use an anonymous type to wrap it up arbitrarily:
Or, if you’re doing that often, you might consider structuring your object to match the JSON you desire:
Serializing an instance of the PersonDTO class would result in the JSON structure you’re looking for.
Thank you very much..
Hopefully, it will solve my problem..
Other quick question … not sure if this is right place or not..
How can i convert back JSON string back to object.. i know how to do it for a simple json string but in my case i got wrapped response from wcf and it’s look like
{“Person”:{“ID”:”123″,”Name”:”Test”},”Company”:{“ID”:”123″,”Name”:”ABC”}}
How would i convert this Json string in to Person and Company object
Please help me..
Thanks for your reply.
It works the same backwards. You’d need an object like:
Then, you can use JavaScriptSerializer to deserialize that JSON into an object of type MyDTO, which has properties matching the JSON’s structure.
Wow… It’s seems some hope for me….
I will try that way.. and update you.
I really appreciate your very very quick help… Thank you very much..
Thanks for you time..
Sorry.. other question..
Hopefully this will solve my problem..
Is it ok if i will create myDTO for all my possible objects, reason for asking on different response JSON string will be different e.g one function return Person and COmpany other function return Person and Address..
So my question if i create general myDTO and pass only require JSON string is it going to be work??
e.g
public class MyDTO {
public Person person { get; set; }
public Company company { get; set; }
public Address address { get; set; }
}
and now i want to desirialze json string which has only Person and Address object or Person and Address object
{“Person”:{“ID”:”123″,”Name”:”Test”},”Company”:{“ID”:”123″,”Name”:”ABC”}}
Or,….
{“Person”:{“ID”:”123″,”Name”:”Test”},”Address”:{“City”:”Toronto″,”Country”:”Canada”}}
Then, I will use JavaScriptSerializer to deserialize that JSON into an object of type MyDTO, will it work or i have to create myDTO for each and every response??
Thank u very much in advance..
If some properties are missing in the JSON, it will work okay and those properties will be null.
One of the best ways to experiment quickly and figure out how these various cases will work is to use LINQPad. You can try all these simple examples in it without worrying about the complexity of building a whole service, client to consume it, etc.
Ok.. I will try that.. Thx
Hi Dave, first of all, thanks for your excellent articles, I have been very helpful in developing in asp.net. I have a question regarding the use of DTO’s, Should I use a dto for a query that only uses a property of the object (the id) to search the database? Or is it more advisable to just send a value?, that is my question.
Thank you in advance and congratulations for your excellent work.
I would just send the value.
Dave, thanks for your quick answer, according to this in the web method should instantiate the object and call the search method, also thought to send a dto with just one property assigned (the id) to implement my application according to dto design pattern, is this a good idea or not?, maybe I’m a little confused trying to follow this pattern.
Greetings.
There’s no need to add the extra complexity of the DTO for a single value. Do something like this:
Dave, this is a great post, got me out of a jam. This does helps to do atomic transactions where user is sending header/details from jQuery and .net service can process it all within one call. Also like the code when handling DTO and to expand it if require additional data…
var DTO = { ‘NewPerson’ : NewPerson, ‘MoreData’ : MoreData };
$.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8″,
url: “PersonService.asmx/AddPerson”,
data: JSON.stringify(DTO),
dataType: “json”
});
Regards
Dermot
For the messy client side code at the beginning of the article, would it be better to begin with a single quote instead of a double quotes for the jquery ajax data property?
Otherwise, I don’t believe the inputs handle values well if the input values themselves contain single or double quotes; e.g., O’Brien.
Good Method. I am very happy to pas whole Object into webservice or WebMethod.
Thanks to every one!!!! and Author for this.
I am following your post, please help me how can I create DTO for my below class
My HTML form looks like
<div id="ModuleDescriptions"> <table > <tr> <td id="ModuleName1" style="width: 400px;"> <input id="ModuleName-1" maxlength="35" name="ModuleName" style="width: 400px; text-transform: uppercase" type="text" value="" /> </td><td id="ModRights1"> <table ><tr> <td style="width: 50px;"><input id="Create-1" class="Rights" type="checkbox" name="Rights" value="C" /> </td> <td style="width: 50px;"><input id="Retrive-1" class="Rights" type="checkbox" name="Rights" value="R"/> </td> <td style="width: 50px;"><input id="Update-1" class="Rights" type="checkbox" name="Rights" value="U" /> </td> <td style="width: 50px;"><input id="Delete-1" class="Rights" type="checkbox" name="Rights" value="D" /> </td></tr></table></td> </tr> <tr> <td style="width: 400px;"> <input id="ModuleName-2" maxlength="35" name="ModuleName" style="width: 400px; text-transform: uppercase" type="text" value="" /> </td><td><table><tr><td style="width: 50px;"><input id="Create-2" class="Rights" type="checkbox" name="Rights" value="C" /> </td> <td style="width: 50px;"><input id="Retrive-2" class="Rights" type="checkbox" name="Rights" value="R"/> </td> <td style="width: 50px;"><input id="Update-2" class="Rights" type="checkbox" name="Rights" value="U" /> </td> <td style="width: 50px;"><input id="Delete-2" class="Rights" type="checkbox" name="Rights" value="D" /> </td> </tr></table></td> </tr> <tr> <td style="width: 400px;"> <input id="ModuleName-3" maxlength="35" name="ModuleName" style="width: 400px; text-transform: uppercase" type="text" value="" /> </td><td><table><tr><td style="width: 50px;"><input id="Create-3" class="Rights" type="checkbox" name="Rights" value="C" /> </td> <td style="width: 50px;"><input id="Retrive-3" class="Rights" type="checkbox" name="Rights" value="R"/> </td> <td style="width: 50px;"><input id="Update-3" class="Rights" type="checkbox" name="Rights" value="U" /> </td> <td style="width: 50px;"><input id="Delete-3" class="Rights" type="checkbox" name="Rights" value="D" /> </td> </tr></table></td> </tr> </table>what i want is to create a Data Transfer object “SRMModules” using JQuery by looping “input id=”ModuleName-X” with corresponding Rights ” “input by check boxes but I dont know how to acheive this.
Dave,
Great posts by the way. I’ve implemented this exactly as you specified, and I can’t get it to work…my added bit was I put the ajax calls into dialog-ui form ala:
I put alerts into the code and everything looks OK, here is my Webservice:
I’ve alternalively been putting the “static” in there and taking it out, unsure exactly when it’s needed (and yes, I did read your post on that as well…but it is still confusing to me)
AjaxSuccess and AjacFailure just do alerts.
Can you see anything glaring?
Thanks,
Brad.
Since this is ASMX, the method doesn’t need to be static (in fact, it won’t work if it is static). The rule of thumb is always static in ASPX and never in ASMX.
I think your problem there is that your DTO on the client-side has a different name than the input parameter to your method. It should be:
Also be aware that the property key names (e.g.
key,levels,textValue, etc) are case-sensitive. So, if your C# SimpleGui type has PascalCase properties instead of camelCase, you’ll need to use the same casing when you build that object on the client-side.Thank you so much. That did it. I’d been working on that intensively for a couple days, and on and off for weeks. I just figured that the “sg” was a instance variable so using the Object type name was sufficent. Boy, was I wrong. I do follow the same caseStyle in the other fields, but thanks for the suggestion.
Also, thanks for the quick response.
Brad.
Hi
I have small problem with my JQuery and Web Service.
My Web Service will take an Class Object and an integer as input parameters while I am calling the web service from JQuery.ajax function passing an javascript object and an integer to the web service and then de-seralize it into class object in my web service and then used,
but I am getting an error as below
Error Occured
{“Message”:”Invalid object passed in,
{\”ThisPrimaryDetails\”:\”{\”FirstName\”:\”Nocolas\”,\”SurName\”:\”Ittamandu\”,\”EMail\”:\”nicloas@gmail.com\”,\”BloodGroup\”:\”O +Ve\”,
\”Mobile\”:\”789546325\”}\”, \”UserId\” : \”3\” }”,
“StackTrace”:” at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer
serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32
depthLimit)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)
at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)
at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData
methodData)”,
“ExceptionType”:”System.ArgumentException”}
here is my javascript code
var UpdatePDetails = {};
var FName = $(“#txtFirstName”).val();
var LName = $(“#txtLastName”).val();
var SName = $(“#txtSurName”).val();
var BGroup = $(“#txtBloodGroup”).val();
var EMail = $(“#txtEMail”).val();
var Mobile = $(“#txtMobile”).val();
UpdatePDetails.FirstName = FName;
UpdatePDetails.LastName = LName;
UpdatePDetails.SurName = SName;
UpdatePDetails.EMail = EMail;
UpdatePDetails.BloodGroup = BGroup;
UpdatePDetails.Mobile = Mobile;
var updetails = JSON.stringify(UpdatePDetails)
$.ajax
({
type: “POST”,
contentType: “application/json; charset=utf-8″,
url: “http://localhost:59415/MyProfile.aspx/UpdatePrimaryDetails”,
data: param,
dataType: “json”,
success: OnUpdateSuccess,
error: OnUpdateFail
});
}
catch (err)
{
alert(“Error Occured in Ajax Function ” + err.Message);
}
and this is my web service code
Dim ThisPrimaryDetailsCopy As PrimaryDetails = New PrimaryDetails
Dim serializer1 As JavaScriptSerializer = New JavaScriptSerializer
ThisPrimaryDetailsCopy = CType(serializer1.DeserializeObject(ThisPrimaryDetails), PrimaryDetails)
Return UserManager.UpdatePrimaryDetails(ThisPrimaryDetailsCopy, UserId).ToString
Very nice article, Dave.
I have learned a lot about JSON from it.
Thanks!
Can I use the same for .ashx handler?
i.e passing object.
IF possible then How?
You could use JavaScriptSerializer or Json.NET to manually handle deserialization and accomplish the same thing. Something like this, following the example in this post where the
PersonJSON comes in through a form variable namedNewPerson:This is an excellent post sir,
The code works wonderfully!!!!
I have manage to insert values in the database but is there anyway to retrieve these values from code behind in asp.net into a json object to be used by the javascript functions in the client side!!!!
I basically need to do this for an events calendar!!!!
Please help me out or could u give me a link as to do so!!!!
Very useful articles Dave, thanks.
May I suggest you write an article about passing complex objects back from ASP.NET to JavaScript. It is not obvious to me when, where or if I should be using the JavaScriptSerializer. For example, do I deserialize objects in ASP before posting them back, or do I deserialize them in JavaScript using JSON. Also, is it necessary to deserialize arrays and value types? And finally, If I am passing an object to the client, do I wrap it in an anonymous type and if so, how to I unwrap it in JavaScript.
Apologies if you have already answered these questions elsewhere.
You shouldn’t need to manually use JavaScriptSerializer for anything, because that’s exactly what ASP.NET is using to provide this feature anyway. Figuring out what client-side structure corresponds to a particular server-side structure can be tricky at first, but is pretty simple once you get a feel for it. For example, a JavaScript array maps to .NET’s Array, List, and other collection types, to answer your question about that.
One of the easiest ways to figure out exactly what to send is to take a look at what the serializer returns for a particular data structure. For example, if you wanted to learn how to send a
List<string>to ASP.NET, you could write a simple service that returns that same data:Making a request to that method would give you:
You can ignore the
.d, since that’s a security wrapper object that only comes down on responses. That leaves you with["foo","bar","baz"]to send, which you could create in JavaScript for use in a DTO to send ASP.NET like this:More complex situations like nested objects and collections can be more complicated, but you can use the same process to figure them out and they use the same basic building blocks.
hi there,
this is an excellent post, thank you.
i was wondering if you had any resources to look at for sending a list of persons from the client. so, instead of sending info about just one person, could i create an array or list on the client and send that to my web service.
thanks in advance.
You can send collections almost the same way. If the WebMethod took a parameter of
List<Person>instead of justPerson, then you could build an array of objects on the client-side and send that instead of the single Person object. Something like this, following from the example in the post and assuming the newList<Person>parameter is calledNewPeople:Thanks again, this is awesome. it works flawlessly.
Hi,
I have to upload file using Jquery-Ajax and Asp.Net WebMethods.
I have tried various options without success :
I am currentlytrying a simple thing as :
Hi Dave,
Do you use the same DTO approach with ASP.NET Web API, or something different?
Hi Dave, grear post!
I am trying to get an object in my web service using web api. I have declared a method InsertStringResource(StringResource stringResource), where StringResource is a class (in EF). It works fine if I pass the json without “name”:
{
“Id”: “2752C4DD-A054-41EB-AFE3-2AA2F8F0AFE3″,
“strresourcecode”: “Test.1234567″,
“LangCode”: “es”,
“value”: “1234567″
}
I want to pass a json like:
{
“stringResource”:
{
“Id”: “2752C4DD-A054-41EB-AFE3-2AA2F8F0AFE3″,
“strresourcecode”: “Test.1234567″,
“LangCode”: “es”,
“value”: “1234567″
}
}
but it is not getting an StringResource object in server side, any idea? I saw in this post that the parameter needs to be called same that the name used in the json…
thanks in advance,
regards,
Fernando
This is a really great! I’m a beginner at javascript and this post rocks! Thanks man
I have used this method in production applications and it is great. Thank you. Using this a starting point I came up with a way to work with the data on the the server side without a facade. With my method all thats needed is an html form with ids that match the sql sever stored procedure parameter names. No maual mapping is needed.
step 1:
change the data option from
to
then in your web service add the following methods
What this does is sends the DTO with a wrapper that is removed in the web service. This plain old JSON is than deserialized into a dictionary object and looped thru to create a proper sqlparameter object. This is than passed to the datalayer.
This saves a lot of time and coding.No facde or mapping code is need. All that is necessary is an html form with id’s named the same as the stored procedure paramaters. I’d be interested to know what others think of this.
You could simplify that a bit by accepting a
Dictionary<string, string>as the input parameter, if that’s what you want:ASP.NET will do all of the [de]serialization work for you, using exactly the same method on the JSS class even. It’s better to work with that feature instead of against, because it’s still going to happen even if you add duplicate effort to do it again manually.
Personally, I prefer having explicit DTO/ViewModel classes. It’s a tiny bit of extra work up front, but I find that it’s nice to have something defining the shape of your data relatively near to the JavaScript. Especially a year or two down the road.
It would also make me nervous if a DBA editing a stored procedure could have side-effects that ripple all the way down to my JavaScript code at such a fundamental level. I can see how that would be a positive feature in some cases though.
If you want to follow that DB-centric pattern farther, you might be interested in ASP.NET Web API’s oData support. You can couple that with something like Breeze to basically query directly against your data layer from JS code.
Dave,
Thanks for your quick response. I implemented your suggestion for simplifying by accepting a Dictionary as the input parameter. It works great. (-:
I agree that in some environments this method could cause issues down the road. It leaves a lot of stuff at an implicit level. But it sure does eliminate lines of code.
I’m going to look into Web API and Breeze. Thanks for the tip and keep up the great work that you do.