I need to pass javascript object to ASP.NET MVC and I’m thinking do it like this:
var p = { account:'123', page:'item' };
var message = escape(p.toSource());
// pass message to action method
That produces something like this (unescaped for readability):
({account:"123", page:"item"})
And in ASP.NET MVC I’m trying to deserialize it and fail.
First, DataContractJsonSerializer was complaining about parenthesis, no problem with that, removed before passing:
{account:"123", page:"item"}
Then it complained about a instead of “, so I’ve tried to serialize datacontract using it, and got:
{"account":"123", "page":"item"}
So, question is, can i use something in ASP.NET MVC, that would work with javascripts toSource format, or am I doing it from scratch wrong?
The
DataContractJsonSerializerclass is pretty strict in terms of JSON format and it adheres to the specification. For example:is invalid JSON according to the specification. You must put double quotes around property names. You could use
JSON.stringifyin order to produce valid JSON:which will produce
{"account":"123","page":"item"}which is now valid JSON. TheJSON.stringifyfunction is natively built into modern browsers and if you want to support legacy browsers you could include json2.js into your page.This being said, you could use the less strict JavaScriptSerializer class, or Json.NET which will accept your invalid JSON string:
And this being said I don’t know why you are deserializing manually the JSON instead of relying on the built in JsonValueProviderFactory:
and to invoke from javascript using AJAX:
See, now you now longer have to worry about any manual serialization/deserialization. Everything is handled by the framework for you.