// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; namespace Microsoft.AspNet.Mvc.ModelBinding { public class DictionaryModelBinder : CollectionModelBinder> { protected override bool CreateOrReplaceCollection(ModelBindingContext bindingContext, IList> newCollection) { CreateOrReplaceDictionary(bindingContext, newCollection, () => new Dictionary()); return true; } private static void CreateOrReplaceDictionary(ModelBindingContext bindingContext, IEnumerable> incomingElements, Func> creator) { var dictionary = bindingContext.Model as IDictionary; if (dictionary == null || dictionary.IsReadOnly) { dictionary = creator(); bindingContext.Model = dictionary; } dictionary.Clear(); foreach (var element in incomingElements) { if (element.Key != null) { dictionary[element.Key] = element.Value; } } } } }