Esempio n. 1
0
        protected override object ExecuteBind(BindingContext context)
        {
            Type keyType   = typeof(TKey);
            Type valueType = typeof(TValue);

            if (!keyType.IsSimple())
            {
                throw Error.UnsupportedDictionaryType(context.ModelType);
            }

            Dictionary <TKey, TValue> convertedValues = new Dictionary <TKey, TValue>();

            foreach (string kvp in context.ValueProvider.Keys)
            {
                string formKey = GetItemKey(kvp, context.ModelName);
                if (String.IsNullOrEmpty(formKey))
                {
                    continue;
                }

                string         keyField    = CreateSubMemberName(context.ModelName, "key");
                IValueProvider keyProvider = new DictionaryValueProvider(
                    CreateKeyBindingData(keyField, formKey));

                BindingContext keyContext = new BindingContext(context, keyType,
                                                               keyField, keyProvider, context.ModelState);

                object boundKey = KeyBinder.Bind(keyContext);
                if (boundKey == null)
                {
                    continue;
                }

                TKey key = Converter.ChangeType <TKey>(boundKey);
                if (!valueType.IsSimple() && convertedValues.ContainsKey(key))
                {
                    continue;
                }

                string         formValue    = CreateSubMemberName(context.ModelName, formKey);
                BindingContext valueContext = new BindingContext(context, valueType,
                                                                 formValue, context.ValueProvider, context.ModelState);

                TValue value = ValidateValue(context, formValue, ValueBinder.Bind(valueContext));
                convertedValues.Add(key, value);
            }

            IDictionary <TKey, TValue> dictionary = (CreateModelInstance(context) as IDictionary <TKey, TValue>);

            if (dictionary == null)
            {
                return(null);
            }

            if (convertedValues.Count == 0)
            {
                return(dictionary);
            }

            CollectionHelpers.CopyDictionary <TKey, TValue>(dictionary, convertedValues);
            return(dictionary);
        }