Pages

Wednesday, February 16, 2011

Post JSON to MVC Controller with XDomainRequest, XmlHttpRequest and jQuery Ajax Call

Once I try to post a JSON to a MVC controller, I use jQuery.post method and all works fine as you can see in this site, the first in the below references.

But when I try to use XDomainRequest or XmlHttpRequest, the JSON parameter at server side has null properties, in others words, the data is sent but not serialized to our serializable Type.

So, in order to receive data at server side, i used the DataContractJsonSerializer class to read the Stream sent in the Request, like this:





Of course, to make use of DataContractJsonSerializer, we need a class representing JSON with [DataContract] attribute and respective [DataMember] just like a WCF service for instance.

Then, the code at server side, looks like this:































And, at client side, making use of XDomainRequest and XmlHttpRequest Objects, and jquery the code is






















This way, you have a MCV controller that can receive JSON using the JSON serializing capacities of MCV3 from XDomainRequest, XmlHttpRequest and jQuery ajax call.


References:
http://lozanotek.com/blog/archive/2010/04/16/posting_json_data_to_mvc_controllers.aspx
http://msdn.microsoft.com/en-us/library/bb412170.aspx
http://msdn.microsoft.com/en-us/library/bb412179.aspx

No comments:

Post a Comment