Search code examples
asp.netjsonhttp-postwebmethodjquery-ajaxq

jQuery AJAX POST object to ASP.Net WebMethod having dynamic datattypes


Hi,
Anyone have an idea what I am doing wrong here. I'm trying to POST JSON objects to ASP.Net WebMethod using jQuery AJAX.

Although I'm getting the objects on server side but not the way I wanted. I wanted customer object to be a simple object so I can access like normal instances e.g. customer.Name, but I can't because it's getting there as dictionary object.

EDIT:: Why JSON is getting on server side as Dictionary object for c# dynamic type?

Here's the quick watch screen-cast; json object not as simple object but coming as dictionary

Here's javascript and server side code.

 function SaveCustomer() {
  var funcParams = JSON.stringify({
    customer: {
      Name: "Name of Customer",
      Title: "President"
    },
    address: {
      Street: "Street",
      City: "",
      Zip: ""
    }
  });

// I tried with the following json parameters but still same result.

var funcParams = "{\"customer\":" + JSON.stringify({ Name: "Name of
 Customer", Title: "President" }) + ",\"address\":" + 
JSON.stringify({ Street: "Street", City: "", Zip: "" }) + "}";
}

 $.ajax({ type: "POST", contentType: "application/json; charset=utf-8",
 dataType: "json", url: "aspxPage.aspx/SaveCustomer", data: funcParams,
 success: function(){  }, error: function(e){alert("Error occured"+e);} 
 })


[WebMethod(EnableSession = true)]
public static string SaveCustomer(dynamic customer, dynamic address)
{
     if(!string.IsNullOrEmpty(customer.Name) && 
         !string.IsNullOrEmpty(customer.Title)....)
      {
           //app logic
      }
}


Solution

  • My suggestion would be to create DTO objects to match that JSON, and then change your method parameters to be of type Customer and Address instead of dynamic. Like this, for example: http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

    You can use Visual Studio's "Paste JSON as Classes" to make creating those classes very quick/easy too.

    If you absolutely cannot use dedicated DTO classes for some reason, try using ExpandoObject as the type of the parameters instead of dynamic. It's been a very long time since I've worked with that and I don't remember if they deserialize correctly in WebMethods, but I think they did. Just understand that the dynamic approach will incur a performance penalty compared to regular DTO POCOs.