In a previous posting, I discussed replacing the stock MVC serializer used for the JsonResult exposed when you use the controller method Json(..) instead of View.
This was all find and dandy. But how – you may wonder – can I call actions that contain complex parameters? Do I need a special binder? Should I write my own?
Here is a function that may help you
The special sauce here is the dataType and contentType together with the POST method. The rest is pretty much how jQuery wants to be called.
On line 6 you will note that I’m POSTing to the same URL as the browser is on – you may want to fiddle with that.
We call this function by hooking up a button, something like:
JSON.stringify(x) would do the trick. You can see it here used on line 12, for the inbound response which I simply stringify and hydrate a response text area. But this is only demo code – you will wire up the success (and failure function- right?) to your own logic.
But back to the core issue: Yes, MVC supports submitting Json and hydrating my controller action, but how do I persuade it to use my custom chosen super duper serializer rather than the stock one?
The answer is: Create a custom ValueProviderFactory and instantiate your favorite serializer in there. A bit of inspection on the MVC source code on CodePlex.com reveals the stock implementation.
Here’s a modified version, which isolates the serialization in a clear way:
It all really boils down to the same ceremony as the default implementation, except on the line
lets to use our own special serializer. Woot!
To use this instead of the built in one, you will modify your global.asax.cs
Application_Start() to include something like
where the built in one gets removed and my custom one gets added. Pretty straightforward.
With this technique and the one described in my previous post, you are ready to use the full power of MVC as an API supporting a nice strongly typed parameter for the back end developer and supporting fully customizable JSON in and out of methods. No real need for other frameworks or technologies for the serving jQuery needs.
Depending on your methods, you may even get away with one set of actions serving both form posts and jQuery invocation.