jQuery AJAX POST object to ASP.Net WebMethod havin

2019-07-12 14:02发布

问题:

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;

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

回答1:

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.



回答2:

I dealt with this scenario just recently. Here is my solution if like me you are set on not creating a DTO class.

1) Pass a serialized JSON string to the WebMethod

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

2) Deserialize the string using JSON.NET and you are good to go.

[WebMethod(EnableSession = true)]
public static string SaveCustomer(string data)
{
   dynamic customer = JsonConvert.DeserializeObject(data);
   customer.Name;
   customer.Address;
  .....
}