Monday, March 26, 2012

Revisited: Posting a JavaScript (JSON) dictionary to an ASP.NET MVC controller

After having read my article Posting a JavaScript (JSON) dictionary to an ASP.NET MVC controller using a custom model binder Benjamin Reich left a comment suggesting that I could combine my custom model binder with his ExtendedJsonValueProviderFactory class. That class returns a custom IValueProvider that provides a model binder with values from a JSON object that is submitted to a controller. Benjamin correctly noticed two things about my onwn code:

  1. My custom DictionaryModelBinder also functions as a IValueProvider (see the AddItemsToDictionary private method in the source code), and there are good reasons to split those functions, as described in a blog post by Phil Haack (thank you for that reference, Benjamin!).
  2. My custom DictionaryModelBinder does not work when the content type of the JavaScript dictionary that is posted to the controller is explicitly set to 'application/json'. I have mentioned the reason for that in the comments below the original post. A quote: "My custom model binder does not bind to real JSON data, but to JavaScript dictionaries (in JSON notation, if I am correct) that are converted to a list of key/value pairs before being posted. The reason for the conversion is that the default content type for the jQuery Ajax post commands is 'application/x-www-form-urlencoded'. This makes the title of my blog post a little bit misleading.
    When you explicitly set contentType: 'application/json; charset=utf-8' using jQuery's $.ajax my DictionaryModelBinder will not work, since it expects its values from the Request.Form collection."

Benjamin has combined my DictionaryModelBinder and his ExtendedJsonValueProviderFactory to a solution that solves both issues. You can check out his code at a GitHub repository. Benjamin has also created a working example.

No comments:

Post a Comment