arrow155 Comments
  1. Rick Strahl
    Apr 07 - 3:53 am

    @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!

  2. Dave
    Apr 07 - 4:07 am

    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

    • Dave Ward
      Apr 07 - 11:41 am

      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):

      // From ToShortDateString()
      new Date('4/7/2009');
       
      // From ToLongDateString()
      new Date('Tuesday April 7, 2009');
       
      // JavaScript's DateTime.Now
      new Date();

      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).

  3. ol3j
    Apr 07 - 6:24 am

    Thanks a lot !
    I am using similar solution but your post is perfect !

  4. Using complex types to make calling services less… complex | Encosia…

    DotNetBurner.com – news and articles about .net DotNetBurner…

  5. Krishna Chaitanya
    Apr 07 - 6:44 am

    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?

  6. Ira
    Apr 07 - 7:06 am

    Great post Dave! I had been wondering how to use complex types while doing ajax calls with jQuery.

  7. Gabriel
    Apr 07 - 10:24 am

    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?

    • Dave Ward
      Apr 07 - 11:03 am

      You’re right. Thanks for pointing that out.

  8. Nick Berardi
    Apr 07 - 11:24 am

    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 } )

    • Dave Ward
      Apr 07 - 11:26 am

      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.

      • Rick
        Feb 22 - 4:19 pm

        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:

        function RangeNotValid(arrParamValues) {
            var arrParamValuesJson = Sys.Serialization.JavaScriptSerializer.serialize(arrParamValues);
         
            var jData;
            var editCk = 'RangeNotValid';
            var options = {
                type: "POST",
                async: false,
                cache: false,
                url: "ScriptWS.asmx/ExecuteCheck",
                data: "{'CheckMethodName':'" + editCk + "', 'ParameterArray':" + arrParamValuesJson + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "html",
                success: function (data) {
                    jData = data;
                },
                error: function (msg) {
                    alert('Error at IsValidDate:' + msg);
                }
            };
            $.ajax(options);
         
            return = jData;
        }

        Here is my VB.NET web service method:

            <WebMethod(EnableSession:=True)> _
            <System.Web.Script.Services.ScriptMethod(ResponseFormat:=System.Web.Script.Services.ResponseFormat.Xml)> _
            Public Function ExecuteEditCheck(ByVal CheckMethodName As String, ByVal ParameterArray() As String) As String
                Dim ParamList As List(Of Object) = ParameterArray.ToList.ConvertAll(Function(s) CObj(s))
        		'Dim ParamList As New List(Of Object)
        		'ParamList.Add(ParameterArray)
                Dim Query As XCQuery = UserSession.CRF.Form.Protocol.Queries.FirstOrDefault(Function(Q As XCQuery) Q.Script.FunctionName = CheckMethodName)
         
        		Dim ret As String = New XCPatientQuery(Query).Run(ParamList).ToString
        		Return ret
        		'Return New XCPatientQuery(Query).Run(ParamList).ToString
            End Function

        Thanks

        • Rick
          Feb 23 - 2:31 pm

          I tested that stringify works in IE8, FF, and Safari without JSON2.js so I’m going to use that :)

          var arrParamValuesJson = JSON.stringify(arrParamValues);
  9. Tobias
    Apr 07 - 12:14 pm

    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)

  10. Bertrand Le Roy
    Apr 07 - 12:52 pm

    @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.

    • Dave Ward
      Apr 07 - 5:12 pm

      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:

      var inputs = document.getElementsByTagName('input');
       
      for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type === 'text') {
          NewPerson[inputs[i].id] = inputs[i].value;
        }
      }
  11. CurlyFro
    Apr 07 - 1:01 pm

    jQuery also has a plugin called $.toJSON(NewPerson)

    • Dave Ward
      Apr 07 - 5:03 pm

      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.

  12. Josh Holmes
    Apr 07 - 2:52 pm

    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;
    }

  13. DotNetShoutout
    Apr 08 - 12:57 am

    Using complex types to make calling services less… complex | Encosia…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  14. Lloyd George
    Apr 08 - 10:00 pm

    As usual.. too good.Thanks for such nice and informative articles.Keep going!!

  15. Claude Plante
    Apr 09 - 8:48 am

    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”
    });

  16. Levin
    Apr 09 - 8:52 pm

    Nice post!
    We can also do some filters on the input elements via something like $(“:input”).filter(“[name^='item']“)

    Cool!

  17. [...] Using complex types to make calling services less… complex | Encosia [...]

  18. Amin Sayed
    Apr 16 - 5:31 am

    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()?

  19. Paul Speranza
    Apr 18 - 9:17 am

    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

  20. Ægir Þorsteinsson
    Apr 20 - 12:03 pm

    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/

  21. Ross Dargan
    Apr 21 - 4:54 am

    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.

  22. NTulip
    Apr 21 - 10:07 am

    Very well done. Thank you for writing this.

  23. Jeff
    Apr 22 - 12:32 pm

    great stuff! thanks for sharing!

  24. Jones
    Apr 27 - 5:18 pm

    Nice post…

  25. Anthony
    Apr 29 - 9:31 am

    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?

    • Dave Ward
      Apr 29 - 10:20 am

      I can vouch that it *should* work. In real projects, I generally keep my services in separate subfolders.

      How is it failing? 404? 403?

    • Justin Miller
      Jun 10 - 4:16 pm

      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

  26. LG
    May 09 - 9:59 am

    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??

    • Dave Ward
      May 09 - 11:08 am

      A JavaScript array will translate to a collection on the server-side. If you were to do something like this:

      var PersonA = { };
       
      PersonA.FirstName = "John";
      PersonA.LastName = "Doe";
       
      var PersonB = { };
       
      PersonB.FirstName = "Jane";
      PersonB.LastName = "Doe";
       
      var People = { People : [ PersonA, PersonB ] };

      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.

      • LG
        May 09 - 11:25 am

        Thank you very much Dave,for your quick response.Thanks for your time.

      • rpcutts
        Jun 17 - 6:19 am

        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.

  27. Andrew Webb
    May 11 - 9:12 am

    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.

  28. [...] should point out at this point that there are much better, cleaner ways to achieve this same thing.  However, for the sake of transparency and ease-of-understanding, [...]

  29. Rajeesh
    May 31 - 11:38 pm

    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/

  30. Fred Besterwitch
    Jun 18 - 8:12 pm

    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.

  31. Joel
    Aug 03 - 6:32 pm

    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…

    [WebMethod]
    public void MyWebMethod(uint[,] numbers)

    but i get a “is not supported for deserialization of an array” error.

    Which data types can I use?

    • Dave Ward
      Aug 04 - 9:55 am

      Use uint[][] instead, and that request parameter will work.

    • Mohit Mendiratta
      Aug 04 - 10:25 am

      you can use List to implement this.

      let me know i u need the code..

  32. Anis Ahmad
    Aug 12 - 12:30 am

    Great article as it shows clarity of mind…

  33. Joel
    Aug 13 - 4:18 pm

    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.

    • Joel
      Aug 13 - 11:30 pm

      That first paragraph should end: “The object I want to serialize contains a List<CustomObject>, where CustomObject contains a couple of primitive types.”

    • Dave Ward
      Aug 14 - 1:07 am

      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.

      • Joel
        Aug 14 - 2:06 am

        Thanks very much Dave. I appreciate your advice.

  34. Aashish Gupta
    Sep 06 - 1:12 am

    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

  35. Jie Li
    Oct 10 - 10:17 pm

    I think it may be too oblivious. This method needs to be static, right?

    [WebMethod]
    public static void AddPerson(Person NewPerson)

    • Dave Ward
      Oct 10 - 11:39 pm

      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.

  36. Jie Li
    Oct 11 - 11:09 am

    Thanks for the reply. I really enjoy your articles.

  37. Dinesh K Mandal
    Oct 23 - 10:31 am

    It’s really a great post. Thanks for your valuable post.

  38. Ashwatha
    Dec 23 - 4:02 am

    Great post, It changed my application architecture,
    Dave Is there anything like this in Java Web Services?

    • Dave Ward
      Jan 02 - 12:27 pm

      I’m not familiar enough with Java to know specifically what its counterpart of this is, but there should definitely be one.

  39. Daivd
    Feb 16 - 10:54 am

    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?

  40. Vijay anand
    Feb 19 - 3:29 am

    Great post. Really informative. I’m a beginner. It’s really useful for me. Great site!

  41. Eric Stevens
    Mar 02 - 9:18 pm

    How does the web service handle the dto object?

    • Dave Ward
      Mar 02 - 9:29 pm

      The “ScriptService” functionality handles that automatically. It’s similar to MVC’s model binding approach.

  42. valse
    Mar 17 - 4:59 am

    In my post I explain how to pass generic unknown types.

  43. Jitendra
    Apr 03 - 12:41 am

    It’s a very nice artical.

    Keep it up…..

  44. Cristiano Borges
    Apr 14 - 11:43 am

    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?

    • Dave Ward
      Apr 14 - 12:57 pm

      Are you using a Page Method or a separate ASMX ScriptService? If it’s a ScriptService, the AddPerson method should not be static.

  45. Ferrol
    Apr 16 - 5:28 pm

    Thank you Dave, for this excellent update. I just rewrote my code! Never too late to learn.

  46. VizMan
    Apr 19 - 12:02 pm

    Is it possible to pass an array of objects of different object types in one JSON request?

    • Dave Ward
      Apr 19 - 3:45 pm

      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?

      • VizMan
        Apr 19 - 4:52 pm

        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.

        • Dave Ward
          Apr 19 - 11:53 pm

          You can do that. Hers’s an example of that kind of nesting:

          public class FatherDTO
          {
            public string Name { get; set; }
            public List<Son> Sons { get; set; }
          }
           
          [WebMethod]
          public void Save(ParentDTO input)
          {
            input.Save();
           
            foreach(Son son in input.Sons)
              son.Save();
          }

          On the client-side, collections like List and arrays correspond to a JavaScript array. So, your object would look something like:

          var Father = {};
           
          Father.Name = "Dad!";
           
          Father.Sons = [];
           
          Father.Sons[0] = {};
          Father.Sons[0].Name = "Eldest Child";
           
          // Or, you can do this:
          var son = {};
           
          son.Name = "Younger Child";
           
          Father.Sons.push(son);

          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.

  47. Dan
    Apr 28 - 4:29 pm

    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 Class

    The 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 Function

    I’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?

    • Dave Ward
      Apr 28 - 4:58 pm

      That looks correct to me, and is within JavaScriptSerializer’s capabilities. What specific error is being returned from the server?

  48. Dan
    Apr 29 - 1:20 pm

    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?

    • Dave Ward
      Apr 29 - 1:36 pm

      I ran a quick test with this service:

        [System.Web.Script.Services.ScriptService]
        public class WebService1 : System.Web.Services.WebService
        {
       
          [WebMethod]
          public Guid HelloWorld(Guid input)
          {
            return input;
          }
        }

      Calling it like this:

      $.ajax({ 
        type: 'POST', 
        dataType: 'json', 
        contentType: 'application/json', 
        url: '/Services/WebService1.asmx/HelloWorld', 
        data: '{"input":"ac7f5305-304a-4ec9-9c54-8c0f9a027633"}' })

      And it appeared to work okay:

      There must be something else going on in your situation.

  49. Dan
    Apr 29 - 2:27 pm

    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!

  50. Gopinath Sundharam
    May 07 - 2:15 am

    Thanks a lot. Lucid explanation.

  51. Legends
    Jun 04 - 8:32 am

    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 !!!

  52. Mark
    Jul 22 - 12:11 pm

    Dave, great post! Part two would have to include the addition of client side validation.

  53. Darrell Russell
    Jul 29 - 11:09 am

    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.

  54. Jerry Gilmore
    Aug 25 - 12:31 pm

    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.

    • Dave Ward
      Aug 25 - 12:41 pm

      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:

      var DTO = { 'NewPerson' : NewPerson };

      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.

  55. Jerry Gilmore
    Aug 25 - 12:49 pm

    Ah never mind figured it out… silly mistake. Parameter variable name wasn’t matching because I had a typo. Doh!

  56. Joel Harris
    Oct 05 - 5:23 pm

    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:

    [WebMethod(EnableSession = true)]
    public void ExportCsv(MyObject theObject)

    …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?

    • Dave Ward
      Oct 05 - 11:32 pm

      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.

      • Joel Harris
        Oct 06 - 9:22 am

        Thanks Dave. Given your response, I realize this is an inappropriate forum for the question. I appreciate your expertise and kind advice.

  57. Jason
    Nov 11 - 6:15 am

    Thanks Dave.
    My problem is a bit more complex though. What would you do in the following scenario:

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

    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.

    • Jason
      Nov 11 - 7:12 am

      Nevermind. I think i figured it out.

      function newPerson()
      {
         var other = new Other();
         this.Other = other; 
      }
       
      function Other()
      {
         this.FirstName = $(“#FirstName”).val(); etc
      }
      • Dave Ward
        Nov 13 - 12:05 am

        You can simplify that a bit, like this:

        var NewPerson = {};
         
        NewPerson.Other = {};
         
        NewPerson.Other.FirstName = $('#FirstName').val();
        NewPerson.Other.LastName = $('#LastName').val();
        NewPerson.Other.Address = $('#Address').val();
        NewPerson.Other.City = $('#City').val();
        NewPerson.Other.State = $('#State').val();
        NewPerson.Other.Zip = $('#Zip').val();
  58. SohelElite
    Dec 14 - 7:31 am

    G8 post you make my day!

  59. Mesifn
    Dec 17 - 4:36 pm

    Very Great Post. Thanks Dave!

  60. Jose
    Jan 27 - 3:44 pm

    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

    //i made everything strings to match the current example
        public string ProductID { get; set; }
        public string Name { get; set; }
        public string Price { get; set; }
        public string Peso { get; set; }
        public string Modelo { get; set; }
        public string Condition { get; set; }
     
        public void Add()
        {
            //In here the code to insert the actual product to the database
        }

    then i have the WebService which should be really straight

        [WebMethod]
        public void AddProduct(Product NewProduct)
        {
            NewProduct.Add();
        }

    The Javascript

        var p = {};
        $(':text').each(function(){
           p[this.id] = this.value;
        });
        var DTO = {'NewProduct' : p};
        $.ajax({
           type: "POST",
           contentType: "application/json; charset=utf-8",
           url: "Producto.asmx/AddProduct",
           data: JSON.stringify(DTO),
           dataType: "json"
        });

    and finally the html

     
     
     
     
     
     
     
                    Product ID:
     
     
     
                    Name:
     
     
     
                    Price:
     
     
     
                    Peso:
     
     
     
                    Modelo:
     
     
     
                    Condition:

    Thanks in advance

    • Jose
      Jan 27 - 3:49 pm

      Sorry about the html anyway i make sure that the input text id’s match my class Product, no doubt in that.

    • Dave Ward
      Jan 27 - 4:03 pm

      Are you getting a JavaScript error? If you inspect the request in Firebug, do you see the correct JSON being sent to the server?

  61. Jose
    Jan 27 - 8:32 pm

    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!!!!

  62. Philip
    Mar 02 - 2:40 pm

    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.

    • Philip
      Mar 03 - 12:54 pm

      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.

      var data = new Object();
      data.__type = "Namespace.ClassType"; //don't forget namespace, which will be at least your project name
  63. Shotemba
    Mar 03 - 3:52 am

    Just what I was looking for, awesome.

  64. [...] http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/ (referência para enviar um objeto ao servidor) [...]

  65. maksoud
    Jul 12 - 9:46 am

    thx for share

  66. [...] devices. I’ve researched several great articles on the client-side (Android) including this Encosia article and sending JSON object with [...]

  67. Shauhin
    Jul 26 - 11:36 pm

    Hi.
    Special thanks for your pretty posts :)
    Can we use jQuery serializer API and mapping serialized data to C# object?

  68. C-Jabbour
    Oct 13 - 11:14 am

    Excellent article!! I knew all of this was possible but was wrestling with the syntax for about an hour. Works like a charm. Thanks!!

  69. Alon
    Dec 13 - 11:20 am

    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

    • Dave Ward
      Dec 13 - 12:54 pm

      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.

      • Alon
        Dec 13 - 2:34 pm

        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

        • Dave Ward
          Dec 13 - 3:21 pm

          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:

          {"RecsToSave":"{\"F1\":789,\"F2\":101,...}"}

          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.

          • Alon
            Dec 13 - 3:28 pm

            OK, thank you very much for the support and for a great set of articles!!

  70. Dan
    Dec 13 - 2:11 pm

    Dave, if I remember correctly, Dictionary isn’t serializable.

    • Dave Ward
      Dec 13 - 2:16 pm

      JavaScriptSerializer handles Dictionary okay (even with a dynamic value type). You can run this in LINQPad for a quick demo:

      Dictionary<string, dynamic> d = new Dictionary<string, dynamic>();
       
      d.Add("foo", 3);
      d.Add("bar", true);
       
      new JavaScriptSerializer().Serialize(d).Dump();
  71. KS
    Dec 15 - 10:43 pm

    @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(),

    • Dave Ward
      Dec 16 - 12:15 am

      In C#, you can use JavaScriptSerializer to build JSON strings.

      • KS
        Dec 16 - 8:10 am

        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

        • Dave Ward
          Dec 16 - 2:09 pm

          You can use an anonymous type to wrap it up arbitrarily:

          Person p = new Person() {
            Name = "testname",
            Phone = "0000000000"
          };
           
          var result = new {
            person = p
          };
           
          // This will result in what you're after.
          string json = new JavaScriptSerializer().Serialize(result);

          Or, if you’re doing that often, you might consider structuring your object to match the JSON you desire:

          public class Person {
            public string Name { get; set; }
            public string Phone { get; set; }
          }
           
          public class PersonDTO {
            public Person person { get; set; }
          }

          Serializing an instance of the PersonDTO class would result in the JSON structure you’re looking for.

          • KS
            Dec 16 - 2:21 pm

            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.

            • Dave Ward
              Dec 16 - 2:22 pm

              It works the same backwards. You’d need an object like:

              public class MyDTO {
                public Person Person { get; set; }
                public Company Company { get; set; }
              }

              Then, you can use JavaScriptSerializer to deserialize that JSON into an object of type MyDTO, which has properties matching the JSON’s structure.

              • KS
                Dec 16 - 2:32 pm

                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..

                • KS
                  Dec 16 - 2:45 pm

                  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..

                  • Dave Ward
                    Dec 16 - 2:49 pm

                    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.

                    • KS
                      Dec 16 - 3:02 pm

                      Ok.. I will try that.. Thx

  72. Oscar
    Dec 18 - 11:30 pm

    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.

  73. Oscar
    Dec 19 - 12:10 am

    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.

    • Dave Ward
      Dec 19 - 2:36 am

      There’s no need to add the extra complexity of the DTO for a single value. Do something like this:

      [WebMethod]
      public List<SearchResult> Search(string SearchTerm) {
        return YourSearchMethod(SearchTerm);
      }
  74. dermot mcevoy
    Dec 30 - 10:27 am

    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

  75. Matt
    Mar 31 - 1:45 pm

    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?

    data: '{ "FirstName" : ' + JSON.stringify($("#FirstName").val()) + ', '
                + '"LastName" : ' + JSON.stringify($("#LastName").val()) + '}',

    Otherwise, I don’t believe the inputs handle values well if the input values themselves contain single or double quotes; e.g., O’Brien.

  76. Nilesh
    May 04 - 4:38 am

    Good Method. I am very happy to pas whole Object into webservice or WebMethod.
    Thanks to every one!!!! and Author for this.

  77. Zoina
    May 06 - 8:44 am

    I am following your post, please help me how can I create DTO for my below class

            public class SRMForm : IOracleCustomType
            {
            [OracleObjectMappingAttribute("UCA_APP_CATEGORY")]
            public virtual string uca_app_category    {get;set;}
     
            [OracleObjectMappingAttribute("MODULES")]
            public virtual SRMModules uca_module_description    {get;set;}
           }
     
          public class SRMRights : SRMForm
          {
            [OracleObjectMappingAttribute("CRT")]
            public virtual string Create     {get;set;}
     
            [OracleObjectMappingAttribute("RTV")]
            public virtual string Retrive     {get;set;}
     
            [OracleObjectMappingAttribute("UPD")]
            public virtual string Update     {get;set;}
     
            [OracleObjectMappingAttribute("DLT")]
            public virtual string Delete     {get;set;}
        }
     
     
        public class SRMModules : SRMForm 
        {
            [OracleObjectMappingAttribute("MODULE_NAME")]
            public virtual string ModuleName     {get;set;}
     
            [OracleObjectMappingAttribute("RIGHTS")]
            public virtual SRMRights ModuleRights     {get;set;}
        }

    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.

  78. [...] ASMX web services from an ajax call is a bit different.I referred to Dave Wards article, “Using complex types to make calling services less… complex” and focused on the following solution that worked for me.  I tried a million things that [...]

  79. BradL
    Jun 18 - 4:20 pm

    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:

    $(function () {
        $("#dialog-simple").dialog(
        {
            autoOpen: false,
            height: 300,
            width: 450,
            modal: true,
            buttons: {
                "Save": function () {
                    editableControl[0].innerHTML = $(".gui_text").val();
                    ... //other code that isn't relevant
                    var SimpleGui = new Object();  //I also tried ... = { }; 
     
                    SimpleGui.key = guiKey;
                    SimpleGui.levels = $('input[id$="hidden_Levels"]').val();
                    SimpleGui.effectiveDate = $('.gui_date_eff').val();
                    SimpleGui.terminationDate = $('.gui_date_trm').val();
                    SimpleGui.textValue = $('.gui_text').val();
     
                    var DTO = { 'SimpleGui': SimpleGui };
     
                    $.ajax({
                        type: "POST",
                        url: "GuiConfigWS.asmx/SaveSimpleToDB",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(DTO),
                        success: AjaxSuccess,
                        error: AjaxFailure
                    }); //end of ajax call
     
                    $(this).dialog("close");
                    return false;
                }, //end of Save button
                "Cancel": function () {
                    $(this).dialog("close");
                    return false;
                } //End of Cancel button
            } //end of buttons
        }); //end of dialog
    });  //end of anonymous function

    I put alerts into the code and everything looks OK, here is my Webservice:

        [System.Web.Script.Services.ScriptMethod]
        [WebMethod]
        public static string SaveSimpleToDB(SimpleGui sg)      {
            return "success!!!";  //temp return until the rest of the code is written.
        } //end of SaveSimpleToDB

    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.

    • Dave Ward
      Jun 18 - 4:34 pm

      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:

      var DTO = { 'sg' : SimpleGui };

      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.

      • BradL
        Jun 19 - 8:39 am

        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.

  80. Ganesh
    Aug 20 - 12:20 am

    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

  81. Francisco Arena
    Aug 30 - 1:46 pm

    Very nice article, Dave.

    I have learned a lot about JSON from it.

    Thanks!

  82. Gurinder
    Nov 16 - 11:09 am

    Can I use the same for .ashx handler?
    i.e passing object.
    IF possible then How?

    • Dave Ward
      Nov 17 - 4:24 pm

      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 Person JSON comes in through a form variable named NewPerson:

      public void ProcessRequest(HttpContext context) {
        Person NewPerson = new JavaScriptSerializer().Deserialize<Person>(context.Request.Form["NewPerson"])
       
        NewPerson.Save();
      }
  83. Darrel Viegas
    Jan 11 - 12:12 pm

    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!!!!

  84. Steve
    Jan 24 - 8:09 am

    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.

    • Dave Ward
      Jan 24 - 10:11 am

      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:

      [WebMethod]
      public List<string> Test() {
        return new List<string> { "foo", "bar", "baz" };
      }

      Making a request to that method would give you:

      {"d":["foo","bar","baz"]}

      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:

      var strings = [ "foo", "bar", "baz" ];

      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.

  85. Ashwin
    Jan 24 - 2:24 pm

    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.

    • Dave Ward
      Jan 24 - 2:38 pm

      You can send collections almost the same way. If the WebMethod took a parameter of List<Person> instead of just Person, 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 new List<Person> parameter is called NewPeople:

      var People = [ ],
          Person1 = { },
          Person2 = { };
       
      Person1.FirstName = $("#FirstName1").val();
      Person1.LastName = $("#LastName2").val();
       
      People.push(Person1);
       
      Person2.FirstName = $("#FirstName2").val();
      Person2.LastName = $("#LastName2").val();
       
      People.push(Person2);
       
      // Create a data transfer object (DTO) with the proper structure.
      var DTO = { 'NewPeople' : People };
       
      $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "PersonService.asmx/AddPerson",
        data: JSON.stringify(DTO),
        dataType: "json"
      });
  86. Ashwin
    Jan 24 - 2:52 pm

    Thanks again, this is awesome. it works flawlessly.

  87. vikas meht
    Mar 02 - 1:50 pm

    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 :

    file = $form.data('input');
    jqxhr = $.ajax({
                        url: "default.aspx/UploadMethod",
                        data: file,
                        cache: false,
                        contentType: false,
                        processData: false,
                        type: 'POST',
                        xhr: function () {
                            var req = $.ajaxSettings.xhr();
                            if (req) {
                                req.upload.addEventListener('progress', function (ev) {
                                    //Display progress Percentage
                                    progress = Math.round(ev.loaded * 100 / ev.total);
                                    $percentage.text(progress.toString() + '%');
                                    $progressBar.progressbar({
                                        value: progress
                                    });
                                }, false);
                            }
                            return req;
                        }
                    })
    				.success(function (data) {
    				    afterEachUpload($form.attr('id'), data);
    				})
    				.error(function (jqXHR, textStatus, errorThrown) {
    				    afterEachUpload($form.attr('id'), null, textStatus, errorThrown);
    				})
    				.complete(function (jqXHR, textStatus) {
    				    $progressBar.progressbar({
    				        value: 100
    				    });
    				    $percentage.text('100%');
     
    				    uploadQueue();
    				});
     [WebMethod]
            public static string UploadMethod(HttpPostedFile PostedFile)
            {
                return "success";
            }
  88. Matt
    Mar 20 - 6:10 pm

    Hi Dave,

    Do you use the same DTO approach with ASP.NET Web API, or something different?

  89. Fernando
    Apr 06 - 5:31 pm

    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

  90. limegreen
    May 17 - 4:04 am

    This is a really great! I’m a beginner at javascript and this post rocks! Thanks man

  91. Joel Erenberg
    May 19 - 9:39 am

    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

     data: JSON.stringify(DTO)

    to

     data: "{'names' : '" + JSON.stringify(DTO) + "'}",

    then in your web service add the following methods

    [WebMethod]
            public string GetEmployees(string names)
            {
                int startPos = names.IndexOf(":");
     
                names = names.Substring(startPos + 1, ((names.Length - startPos) - 1) - 1);
     
                SqlParameter[] param = GetEmployeesSQLParameters(names);
     
                //enter stored procedure name as 1st parm
                DataTable dt = ExecuteDataTable("GetEmployees", param);
     
                JSONDataTableSerializer js = new JSONDataTableSerializer();
                string jData = js.GetJson(dt);
                return jData;
     
            }
            private SqlParameter[] GetEmployeesSQLParameters(string names)
            {
                var jss = new JavaScriptSerializer();
     
                var dict = jss.Deserialize<Dictionary<string, string>>(names);
     
                int parmCount = dict.Count();
     
                int counter = 0;
     
                SqlParameter[] param = new SqlParameter[parmCount];
     
                foreach (KeyValuePair<string, string> item in dict)
                {
                    param[counter] = new SqlParameter("@" + item.Key, item.Value);
     
                    counter++;
                }
     
                return param;
            }

    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.

    • Dave Ward
      May 19 - 3:31 pm

      You could simplify that a bit by accepting a Dictionary<string, string> as the input parameter, if that’s what you want:

      public string GetEmployees(Dictionary<string, string> names)

      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.

      • Joel Erenberg
        May 19 - 11:22 pm

        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.

  92. Arshi Khan
    Oct 24 - 2:33 pm

    Fantastic post – 10 out of 10. You made complex ajax calls so simple. Please keep up with your good work.

  93. Sheryar Nizar
    Dec 29 - 11:19 pm

    This is AWESOME. keep up the good work by serving the knowledge and intellect.

  94. Upendra Watwe
    Jan 09 - 2:09 pm

    Hi Dave,
    Thanks for the wonderfully clear post about using json with webservices esp when the need is to pass complex types to web methods.
    shared this solution on the XDK forums so others can also benefit.
    https://forums.html5dev-software.intel.com/viewtopic.php?f=34&t=5034

  95. Dan
    Jan 09 - 2:18 pm

    I love how this post is still relevant 5 years later!

  96. Andrew
    Mar 11 - 11:13 am

    I’d like to know how to generate a Json table of simple records from VBScript / Access query using ASP.net, to send back to the client: currently I have the serialisation problem (quotes within quotes – shame this cannot use single quotes to help).

    I have looked a few times and can’t see an example here, in particular I’d like to be able to do it without setting up classes; if needed, where exactly do they go in the WebMethod code (or elsewhere on the code-behind page)

  97. jarajesh
    Apr 21 - 11:51 am

    $.ajax({
    type: “POST”,
    contentType: “application/json; charset=utf-8″,
    url: “PersonService.asmx/AddPerson”,
    data: “{‘NewPerson’:” + JSON.stringify(NewPerson) + “}”,
    dataType: “json”
    });

    while submitting this json i was getting the error warning:illegal/unquoted identifier

    then added double quotes for NewPerson as follow
    data: “{“+’”‘+”NewPerson”+’”‘+”:” + JSON.stringify(NewPerson) + “}”,

    then I was able to get it parsed and was able to decode in php until then it was throwing error

Leave a Reply

Mobile Theme