Improved model binder for dictionaries

Topics: ASP.NET MVC
Apr 3, 2012 at 11:48 AM
Edited Apr 3, 2012 at 11:49 AM

A while back I wrote an extension/replacement to the DefaultModelBinder that more easily allows dictionaries to be bound. It's basically an extension to the existing concept of array bindings, except with support to the generic dictionary. For example, if the post data is this:

 

capitals[Australia]=Canberra&capitals[USA]=Washington DC

 

and the action method is:

 

public ActionResult SaveCapitals(Dictionary<string, string> capitals)

 

You will get the dictionary "capitals" with

 

{ "Australia", "Canberra" },
{ "USA", "Washington DC" }

It works with complex bindings as well (i.e. objects with dictionaries/dictionaries of objects)

This is more intuitive than the current implementation where you specify separately key and value fields i.e.

 

capitals[0].Key=Australia&capitals[0].Value=Canberra

 

More detailed explanation here: http://siphon9.net/loune/2009/12/a-intuitive-dictionary-model-binder-for-asp-net-mvc/

The full source code is here: https://github.com/loune/MVCStuff/blob/master/Extensions/DefaultDictionaryBinder.cs

I would love to adapt it for inclusion in the official MVC tree. Let me know what you guys think.