UPDATE
Based on the Jeroen blog post (see his answer below, with a link) and the brain flash I received after re-examining my code, I updated ExtendedJsonValueProviderFactory so that it always correctly creates a BackingStore for the top-level dictionary submitted via JSON.
The code is available on GitHub at https://github.com/counsellorben/ASP.NET-MVC-JsonDictionaryBinding , and a working example is http://oss.form.vu/json-dictionary-example/ .
By removing the current JsonValueProviderFactory and replacing the one that can handle dictionary creation, you can link your dictionary. First, as Kate pointed out, be sure to close your dictionary inside “filterItem” in your Javascript, since this is the name of the model variable in your controller’s action, and for JSON, the name of the variable in the controller’s action must match the name of the returned Json element. In addition, when passing a class, any nested elements must match the property names in the class.
Then create the ExtendedJsonValueProviderFactory class as follows:
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Web.Script.Serialization; public sealed class ExtendedJsonValueProviderFactory : ValueProviderFactory { private void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value) { IDictionary<string, object> d = value as IDictionary<string, object>; if (d != null) { foreach (KeyValuePair<string, object> entry in d) { if (entry.Key.EndsWith("Dictionary", StringComparison.CurrentCulture)) CreateDictionary(backingStore, entry); else AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value); } return; } IList l = value as IList; if (l != null) { for (int i = 0; i < l.Count; i++) { AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]); } return; }
You may notice that this class is almost identical to the standard of the JsonValueProviderFactory class, with the exception of the extension for creating an entry in DictionaryValueProvider of type Dictionary<string,string> . You should also notice that for processing as a dictionary, the element must have a name ending in "Dictionary" (and although I think this is a significant smell of code, I can’t think of an alternative alternative at this time ... I am open to suggestions).
Then add the following to Application_Start in Global.asax.cs :
var j = ValueProviderFactories.Factories.FirstOrDefault(f => f.GetType().Equals(typeof(JsonValueProviderFactory))); if (j != null) ValueProviderFactories.Factories.Remove(j); ValueProviderFactories.Factories.Add(new ExtendedJsonValueProviderFactory());
This will remove the standard JsonValueProviderFactory and replace it with our extended class.
The final step: enjoy kindness.