ASP.NET MVC Binding to a dictionary

In ASP.NET MVC 4, the default model binder will bind dictionaries using the typical dictionary indexer syntax property[key].

If you have a Dictionary<string, string> in your model, you can now bind back to it directly with the following markup:

<input type="hidden" name="MyDictionary[MyKey]" value="MyValue" />

For example, if you want to use a set of checkboxes to select a subset of a dictionary’s elements and bind back to the same property, you can do the following:

@foreach(var kvp in Model.MyDictionary)
{
    <input type="checkbox" name="@("MyDictionary[" + kvp.Key + "]")"
        value="@kvp.Value" />
}

Leave a Comment