Ejemplo n.º 1
0
        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            // Check for existence of type discriminator field
            string typeDiscrimKey         = CreateSubPropertyName(bindingContext.ModelName, "_TYPEDISC_");
            ValueProviderResult vpDiscrim = bindingContext.ValueProvider.GetValue(typeDiscrimKey);

            if (vpDiscrim != null)
            {
                // check for attribute on property specifying the requested type name is allowed
                string typeName = (string)vpDiscrim.ConvertTo(typeof(string));
                var    attr     = propertyDescriptor.Attributes.OfType <AllowedSubtypesAttribute>().FirstOrDefault();
                if (attr != null && attr.AllowedSubtypeNames.Contains(typeName))
                {
                    // check if the requested type is different from the property type, but assignable to it
                    Type propType = Type.GetType(typeName);
                    if (propType != propertyDescriptor.PropertyType && propertyDescriptor.PropertyType.IsAssignableFrom(propType))
                    {
                        // substitute type of property for specified type
                        IModelBinder newPropertyBinder = Binders.GetBinder(propType);
                        var          propertyMetadata  =
                            ModelMetadataProviders.Current.GetMetadataForType(() => null, propType);
                        ModelBindingContext newBindingContext = new ModelBindingContext()
                        {
                            ModelMetadata = propertyMetadata,
                            ModelName     = bindingContext.ModelName,
                            ModelState    = bindingContext.ModelState,
                            ValueProvider = bindingContext.ValueProvider
                        };

                        return(base.GetPropertyValue(controllerContext, newBindingContext, propertyDescriptor, newPropertyBinder));
                    }
                }
            }
            return(base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder));
        }
Ejemplo n.º 2
0
        protected internal bool TryUpdateModel <TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider) where TModel : class
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            if (valueProvider == null)
            {
                throw new ArgumentNullException("valueProvider");
            }

            Predicate <string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, includeProperties, excludeProperties);
            IModelBinder       binder         = Binders.GetBinder(typeof(TModel));

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)),
                ModelName      = prefix,
                ModelState     = ModelState,
                PropertyFilter = propertyFilter,
                ValueProvider  = valueProvider
            };

            binder.BindModel(ControllerContext, bindingContext);
            return(ModelState.IsValid);
        }
Ejemplo n.º 3
0
        private List <object> getArrayItems(ControllerContext controllerContext, ModelBindingContext bindingContext, string arrayName, Type elementType)
        {
            List <object> items = new List <object>();

            Regex      regex = createKeyRegexp(arrayName);
            List <int> keys  = getKeysInAscendingOrder(controllerContext.HttpContext.Request, regex);

            IModelBinder elementBinder = Binders.GetBinder(elementType);

            foreach (var key in keys)
            {
                ModelBindingContext innerContext = new ModelBindingContext()
                {
                    ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(null, elementType),
                    ModelName      = $"{arrayName}[{key}]",
                    ModelState     = bindingContext.ModelState,
                    PropertyFilter = bindingContext.PropertyFilter,
                    ValueProvider  = bindingContext.ValueProvider
                };

                object element = elementBinder.BindModel(controllerContext, innerContext);
                items.Add(element);
            }

            return(items);
        }
        protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            // need to skip properties that aren't part of the request, else we might hit a StackOverflowException
            string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);

            if (!DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, fullPropertyKey))
            {
                return;
            }

            // call into the property's model binder
            IModelBinder        propertyBinder        = Binders.GetBinder(propertyDescriptor.PropertyType);
            object              originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model);
            ModelBindingContext innerBindingContext   = new ModelBindingContext()
            {
                Model         = originalPropertyValue,
                ModelName     = fullPropertyKey,
                ModelState    = bindingContext.ModelState,
                ModelType     = propertyDescriptor.PropertyType,
                ValueProvider = bindingContext.ValueProvider
            };
            object newPropertyValue = propertyBinder.BindModel(controllerContext, innerBindingContext);

            // validation
            if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue))
            {
                SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
            }
        }
        protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            // need to skip properties that aren't part of the request, else we might hit a StackOverflowException
            string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);

            if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey))
            {
                return;
            }

            // call into the property's model binder
            IModelBinder  propertyBinder        = Binders.GetBinder(propertyDescriptor.PropertyType);
            object        originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model);
            ModelMetadata propertyMetadata      = bindingContext.PropertyMetadata[propertyDescriptor.Name];

            propertyMetadata.Model = originalPropertyValue;
            ModelBindingContext innerBindingContext = new ModelBindingContext()
            {
                ModelMetadata = propertyMetadata,
                ModelName     = fullPropertyKey,
                ModelState    = bindingContext.ModelState,
                ValueProvider = bindingContext.ValueProvider
            };
            object newPropertyValue = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, propertyBinder);

            propertyMetadata.Model = newPropertyValue;

            // validation
            ModelState modelState = bindingContext.ModelState[fullPropertyKey];

            if (modelState == null || modelState.Errors.Count == 0)
            {
                if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue))
                {
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                    OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                }
            }
            else
            {
                SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);

                // Convert FormatExceptions (type conversion failures) into InvalidValue messages
                foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList())
                {
                    for (Exception exception = error.Exception; exception != null; exception = exception.InnerException)
                    {
                        if (exception is FormatException)
                        {
                            string displayName          = propertyMetadata.GetDisplayName();
                            string errorMessageTemplate = GetValueInvalidResource(controllerContext);
                            string errorMessage         = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);
                            modelState.Errors.Remove(error);
                            modelState.Errors.Add(errorMessage);
                            break;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 更新实体对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected new void UpdateModel <TModel>(TModel entity) where TModel : IEntity
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (ValueProvider == null)
            {
                throw new ArgumentNullException("ValueProvider");
            }

            Type type = typeof(T);

            IModelBinder binder = Binders.GetBinder(type);

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => entity, type),
                ModelName      = null,
                ModelState     = ModelState,
                PropertyFilter = null,
                ValueProvider  = ValueProvider
            };

            binder.BindModel(ControllerContext, bindingContext);

            UpdateEntity(entity);
        }
Ejemplo n.º 7
0
        private void BindingProperty(HttpContext httpContext, ModelBindingContext bindingContext, PropertyDescriptor property)
        {
            // 将属性名添加到现有前缀上
            string prefix = $"{bindingContext.ModelName ?? ""}.{property.Name ?? ""}".Trim('.');

            // 针对属性创建绑定上下文
            ModelMetadata       metadata = bindingContext.PropertyMetadata[property.Name];
            ModelBindingContext context  = new ModelBindingContext(bindingContext.ValueProvider)
            {
                ModelName     = prefix,
                ModelMetadata = metadata,
            };

            // 针对属性实施Model绑定并对属性赋值
            // 注意BindModel方法的调用,复杂类型的递归调用就来自于这里
            object propertyValue = Binders.GetBinder(property.PropertyType).BindModel(httpContext, context);

            if (bindingContext.ModelMetadata.ConvertEmptyStringToNull &&
                Object.Equals(propertyValue, String.Empty))
            {
                propertyValue = null;
            }

            context.ModelMetadata.Model = propertyValue;
            property.SetValue(bindingContext.Model, propertyValue);
        }
Ejemplo n.º 8
0
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        IXpoController xpoController = controllerContext.Controller as IXpoController;

        if (xpoController == null)
        {
            throw new InvalidOperationException("The controller does not support IXpoController interface");
        }
        XPClassInfo         classInfo = xpoController.XpoSession.GetClassInfo(modelType);
        ModelBindingContext keyPropertyBindingContext = new ModelBindingContext()
        {
            ModelMetadata = bindingContext.PropertyMetadata[classInfo.KeyProperty.Name],
            ModelName     = classInfo.KeyProperty.Name,
            ModelState    = bindingContext.ModelState,
            ValueProvider = bindingContext.ValueProvider
        };
        PropertyDescriptorCollection properties  = GetModelProperties(controllerContext, bindingContext);
        PropertyDescriptor           keyProperty = properties.Find(classInfo.KeyProperty.Name, false);
        IModelBinder keyPropertyBinder           = Binders.GetBinder(keyProperty.PropertyType);
        object       keyValue = GetPropertyValue(controllerContext, keyPropertyBindingContext, keyProperty, keyPropertyBinder);

        if (keyValue == null)
        {
            return(classInfo.CreateNewObject(xpoController.XpoSession));
        }
        else
        {
            return(xpoController.XpoSession.GetObjectByKey(classInfo, keyValue));
        }
    }
Ejemplo n.º 9
0
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            var fullPropertyKey = CreateSubPropertyName(propertyDescriptor.Name);

            if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey))
            {
                return;
            }

            var propertyBinder        = Binders.GetBinder(propertyDescriptor.PropertyType);
            var originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model);
            var propertyMetadata      = bindingContext.PropertyMetadata[propertyDescriptor.Name];

            propertyMetadata.Model = originalPropertyValue;

            var innerBindingContext = new ModelBindingContext {
                ModelMetadata = propertyMetadata,
                ModelName     = fullPropertyKey,
                ModelState    = bindingContext.ModelState,
                ValueProvider = bindingContext.ValueProvider
            };

            var newPropertyValue = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, propertyBinder);

            propertyMetadata.Model = newPropertyValue;

            var modelState = bindingContext.ModelState[fullPropertyKey];

            if (modelState == null || modelState.Errors.Count == 0)
            {
                if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue))
                {
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                    OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);
                }
            }
            else
            {
                SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);

                foreach (var modelError in modelState.Errors.Where(me => string.IsNullOrEmpty(me.ErrorMessage) && me.Exception != null).ToList())
                {
                    for (var exception = modelError.Exception; exception != null; exception = exception.InnerException)
                    {
                        if (exception is FormatException)
                        {
                            var displayName          = propertyMetadata.GetDisplayName();
                            var errorMessageTemplate = GetValueInvalidResource(controllerContext);
                            var errorMessage         = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);
                            modelState.Errors.Remove(modelError);
                            modelState.Errors.Add(errorMessage);
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var viewModel     = GetCurrentStep();
            var viewModelType = viewModel.GetType();

            //var viewModelBindingContext = CreateViewModelBindingContext(bindingContext, viewModel, viewModelType);

            return(Binders.GetBinder(viewModelType).BindModel(controllerContext, bindingContext));
        }
Ejemplo n.º 11
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var viewModel               = CreateViewModel(bindingContext);
            var viewModelType           = viewModel.GetType();
            var viewModelBindingContext = CreateViewModelBindingContext(bindingContext, viewModel, viewModelType);

            var binder = Binders.GetBinder(viewModelType);
            var result = binder.BindModel(controllerContext, viewModelBindingContext);

            return(result);
        }
        internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType)
        {
            bool stopOnIndexNotFound;
            IEnumerable <string> indexes;

            GetIndexes(bindingContext, out stopOnIndexNotFound, out indexes);
            IModelBinder elementBinder = Binders.GetBinder(elementType);

            // build up a list of items from the request
            List <object> modelList = new List <object>();

            foreach (string currentIndex in indexes)
            {
                string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);
                if (!bindingContext.ValueProvider.ContainsPrefix(subIndexKey))
                {
                    if (stopOnIndexNotFound)
                    {
                        // we ran out of elements to pull
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }

                ModelBindingContext innerContext = new ModelBindingContext()
                {
                    ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(null, elementType),
                    ModelName      = subIndexKey,
                    ModelState     = bindingContext.ModelState,
                    PropertyFilter = bindingContext.PropertyFilter,
                    ValueProvider  = bindingContext.ValueProvider
                };
                object thisElement = elementBinder.BindModel(controllerContext, innerContext);

                // we need to merge model errors up
                AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, subIndexKey, elementType, thisElement);
                modelList.Add(thisElement);
            }

            // if there weren't any elements at all in the request, just return
            if (modelList.Count == 0)
            {
                return(null);
            }

            // replace the original collection
            object collection = bindingContext.Model;

            CollectionHelpers.ReplaceCollection(elementType, collection, modelList);
            return(collection);
        }
Ejemplo n.º 13
0
            public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                Type modelType = bindingContext.ModelType;
                Type idictType = modelType.GetInterface("System.Collections.Generic.IDictionary`2");

                if (idictType != null)
                {
                    Type[] argumetTypes = idictType.GetGenericArguments();

                    object       result      = null;
                    IModelBinder valueBinder = Binders.GetBinder(argumetTypes[1]);

                    foreach (string key in GetValueProviderKeys(controllerContext))
                    {
                        if (!key.StartsWith(bindingContext.ModelName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;
                        }

                        object dictKey;
                        string parameterName = key.Substring(bindingContext.ModelName.Length);
                        try
                        {
                            dictKey = ConvertType(parameterName, argumetTypes[0]);
                        }
                        catch (NotSupportedException)
                        {
                            continue;
                        }

                        ModelBindingContext innerBindingContext = new ModelBindingContext()
                        {
                            ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => null, argumetTypes[1]),
                            ModelName      = key,
                            ModelState     = bindingContext.ModelState,
                            PropertyFilter = bindingContext.PropertyFilter,
                            ValueProvider  = bindingContext.ValueProvider
                        };
                        object newPropertyValue = valueBinder.BindModel(controllerContext, innerBindingContext);

                        if (result == null)
                        {
                            result = CreateModel(controllerContext, bindingContext, modelType);
                        }

                        if (!(bool)idictType.GetMethod("ContainsKey").Invoke(result, new object[] { dictKey }))
                        {
                            idictType.GetProperty("Item").SetValue(result, newPropertyValue, new object[] { dictKey });
                        }
                    }
                    return(result);
                }
                return(new DefaultModelBinder().BindModel(controllerContext, bindingContext));
            }
        protected virtual IModelBinder GetPropertyBinder(PropertyDescriptor property)
        {
            ModelBinderAttribute attribute = property.Attributes
                                             .OfType <ModelBinderAttribute>().FirstOrDefault();

            if (attribute == null)
            {
                return(Binders.GetBinder(property.PropertyType));
            }

            return(attribute.GetBinder());
        }
Ejemplo n.º 15
0
        private object BindDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type idictType)
        {
            Type   modelType = bindingContext.ModelType;
            object result    = null;

            Type[]       ga          = idictType.GetGenericArguments();
            IModelBinder valueBinder = Binders.GetBinder(ga[1]);

            foreach (string key in GetValueProviderKeys(controllerContext))
            {
                bool isMatch = key.StartsWith(bindingContext.ModelName + "[", StringComparison.InvariantCultureIgnoreCase);
                if (isMatch)
                {
                    int endbracket = key.IndexOf("]", bindingContext.ModelName.Length + 1);
                    if (endbracket == -1)
                    {
                        continue;
                    }

                    object dictKey;
                    try
                    {
                        dictKey = ConvertType(key.Substring(bindingContext.ModelName.Length + 1, endbracket - bindingContext.ModelName.Length - 1), ga[0]);
                    }
                    catch (NotSupportedException)
                    {
                        continue;
                    }

                    ModelBindingContext innerBindingContext = new ModelBindingContext()
                    {
                        ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => null, ga[1]),
                        ModelName      = key.Substring(0, endbracket + 1),
                        ModelState     = bindingContext.ModelState,
                        PropertyFilter = bindingContext.PropertyFilter,
                        ValueProvider  = bindingContext.ValueProvider
                    };
                    object newPropertyValue = valueBinder.BindModel(controllerContext, innerBindingContext);

                    if (result == null)
                    {
                        result = CreateModel(controllerContext, bindingContext, modelType);
                    }

                    if (!(bool)idictType.GetMethod("ContainsKey").Invoke(result, new object[] { dictKey }))
                    {
                        idictType.GetProperty("Item").SetValue(result, ((string[])newPropertyValue)[0], new object[] { dictKey });
                    }
                }
            }

            return(result);
        }
    private object UpdateDynamicDictionary(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        var modelList = new List <KeyValuePair <string, object> >();
        var enumerableValueProvider = bindingContext.ValueProvider as IEnumerableValueProvider;

        if (enumerableValueProvider != null)
        {
            var keys   = enumerableValueProvider.GetKeysFromPrefix(bindingContext.ModelName);
            var groups = keys.GroupBy((k) => k.Key.Split('[')[0]);
            foreach (var group in groups)
            {
                if (group.Count() > 1)
                {
                    var valueType = typeof(ICollection <ExpandoObject>);
                    modelList.Add(
                        CreateEntryForModel(
                            controllerContext,
                            bindingContext,
                            valueType,
                            Binders.GetBinder(valueType),
                            bindingContext.ModelName + '.' + group.Key,
                            group.Key));
                }
                else
                {
                    var item      = group.Single();
                    var value     = bindingContext.ValueProvider.GetValue(item.Value);
                    var valueType = value != null && value.RawValue != null ?
                                    typeof(object) : typeof(ExpandoObject);
                    modelList.Add(
                        CreateEntryForModel(
                            controllerContext,
                            bindingContext,
                            valueType,
                            Binders.GetBinder(valueType),
                            item.Value,
                            item.Key));
                }
            }
        }
        var dictionary = (IDictionary <string, object>)bindingContext.Model;

        foreach (var kvp in modelList)
        {
            dictionary[kvp.Key] = kvp.Value;
        }
        return(dictionary);
    }
Ejemplo n.º 17
0
        private object GetParametersFromType(Type parameterType)
        {
            var binder         = Binders.GetBinder(parameterType);
            var model          = Activator.CreateInstance(parameterType);
            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, parameterType),
                ModelName     = "Parameters",
                ModelState    = ModelState,
                ValueProvider = ValueProvider
            };

            binder.BindModel(ControllerContext, bindingContext);
            return(model);
        }
Ejemplo n.º 18
0
        protected void updateModel(M model, FormCollection form)
        {
            Predicate <string> propertyFilter = propertyName => IsPropertyAllowed(propertyName, null, null);
            IModelBinder       binder         = Binders.GetBinder(typeof(M));

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(M)),
                ModelName      = null,
                ModelState     = new ModelStateDictionary(),
                PropertyFilter = propertyFilter,
                ValueProvider  = form
            };

            binder.BindModel(ControllerContext, bindingContext);
        }
Ejemplo n.º 19
0
        private void PopulateParams()
        {
            var modelType           = typeof(IDictionary <SymbolId, object>);
            var request             = ControllerContext.HttpContext.Request;
            var binder              = Binders.GetBinder(modelType);
            var modelBindingContext = new ModelBindingContext
            {
                Model         = new Dictionary <SymbolId, object>(ControllerContext.RouteData.Values.Count + request.QueryString.Count + request.Form.Count),
                ModelName     = "params",
                ModelState    = ModelState,
                ModelType     = modelType,
                ValueProvider = ValueProvider
            };

            _params = binder.BindModel(ControllerContext, modelBindingContext) as IDictionary <SymbolId, object>;
        }
Ejemplo n.º 20
0
        private object BindDictionary(HttpContext httpContext, ModelBindingContext bindingContext)
        {
            Type modelType = bindingContext.ModelType;

            Type[] argumentTypes = modelType.GetGenericArguments();
            Type   keyType       = argumentTypes[0];
            Type   valueType     = argumentTypes[1];
            object model         = CreateModel(httpContext, bindingContext, modelType);

            List <KeyValuePair <object, object> > list = new List <KeyValuePair <object, object> >();
            var isZeroBased = GetIndexes(bindingContext, out var indexes);

            foreach (var index in indexes)
            {
                string prefix = $"{bindingContext.ModelName}.[{index}]";
                if (!bindingContext.ValueProvider.ContainsPrefix(prefix))
                {
                    if (isZeroBased)
                    {
                        break;
                    }

                    continue;
                }

                ModelBindingContext contextForKey = new ModelBindingContext(bindingContext.ValueProvider)
                {
                    ModelMetadata = ModelMetadataProvider.GetMetadataForType(null, keyType),
                    ModelName     = prefix + ".key"
                };

                ModelBindingContext contextForValue = new ModelBindingContext(bindingContext.ValueProvider)
                {
                    ModelMetadata = ModelMetadataProvider.GetMetadataForType(null, valueType),
                    ModelName     = prefix + ".value"
                };

                object key = Binders.GetBinder(keyType)
                             .BindModel(httpContext, contextForKey);
                object value = Binders.GetBinder(valueType)
                               .BindModel(httpContext, contextForValue);
                list.Add(new KeyValuePair <object, object>(key, value));
            }

            ReplaceDictionary(keyType, valueType, model, list);
            return(model);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Adiciona os itens para o dicionário.
        /// </summary>
        /// <param name="dictionary"></param>
        /// <param name="dictionaryType">Tipo do dicionário.</param>
        /// <param name="modelName"></param>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        private void AddItemsToDictionary(IDictionary dictionary, Type dictionaryType, string modelName, ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            List <string> keys    = new List <string>();
            var           request = controllerContext.HttpContext.Request;

            keys.AddRange(((IDictionary <string, object>)controllerContext.RouteData.Values).Keys.Cast <string>());
            keys.AddRange(request.QueryString.Keys.Cast <string>());
            keys.AddRange(request.Form.Keys.Cast <string>());
            Type         dictionaryValueType   = dictionaryType.GetGenericArguments()[1];
            IModelBinder dictionaryValueBinder = Binders.GetBinder(dictionaryValueType);

            foreach (string key in keys)
            {
                string dictItemKey    = null;
                string valueModelName = null;
                if (!key.Equals("area", StringComparison.InvariantCultureIgnoreCase) && !key.Equals("controller", StringComparison.InvariantCultureIgnoreCase) && !key.Equals("action", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (key.StartsWith(modelName + "[", StringComparison.InvariantCultureIgnoreCase))
                    {
                        int endIndex = key.IndexOf("]", modelName.Length + 1);
                        if (endIndex != -1)
                        {
                            dictItemKey    = key.Substring(modelName.Length + 1, endIndex - modelName.Length - 1);
                            valueModelName = key.Substring(0, endIndex + 1);
                        }
                    }
                    else
                    {
                        dictItemKey = valueModelName = key;
                    }
                    if (dictItemKey != null && valueModelName != null && !dictionary.Contains(dictItemKey))
                    {
                        object dictItemValue = dictionaryValueBinder.BindModel(controllerContext, new ModelBindingContext(bindingContext)
                        {
                            ModelName     = valueModelName,
                            ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, dictionaryValueType)
                        });
                        if (dictItemValue != null)
                        {
                            dictionary.Add(dictItemKey, dictItemValue);
                        }
                    }
                }
            }
        }
        public ActionResult EnrolleeInfo(FormCollection form = null)
        {
            if (Request.HttpMethod == "GET")
            {
                if (PropertyBag.Customer.Enroller == null)
                {
                    return(Checkout());
                }

                return(View(PropertyBag));
            }
            else
            {
                // Fixes issues with payment methods not being saved correctly
                PropertyBag.PaymentMethod = null;

                var type           = typeof(EnrollmentPropertyBag);
                var binder         = Binders.GetBinder(type);
                var bindingContext = new ModelBindingContext()
                {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => PropertyBag, type),
                    ModelState    = ModelState,
                    ValueProvider = form,
                };
                binder.BindModel(ControllerContext, bindingContext);

                // Set shipping address
                if (PropertyBag.UseSameShippingAddress)
                {
                    PropertyBag.ShippingAddress           = new ShippingAddress(PropertyBag.Customer.MainAddress);
                    PropertyBag.ShippingAddress.FirstName = PropertyBag.Customer.FirstName;
                    PropertyBag.ShippingAddress.LastName  = PropertyBag.Customer.LastName;
                    PropertyBag.ShippingAddress.Phone     = PropertyBag.Customer.PrimaryPhone;
                    PropertyBag.ShippingAddress.Email     = PropertyBag.Customer.Email;
                }

                ExigoDAL.PropertyBags.Update(PropertyBag);

                return(new JsonNetResult(new
                {
                    success = true
                }));
            }
        }
Ejemplo n.º 23
0
    private GenericModel CreateGenricModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        GenericModel        model   = new GenericModel();
        ModelBindingContext context = CreateGenericFieldBindingContext(bindingContext, model);

        foreach (PropertyDescriptor descriptor in GetFilteredModelProperties(controllerContext, context))
        {
            string prefix = CreateSubPropertyPrefix(context.ModelName, descriptor.Name);
            ModelBindingContext propertyContext = new ModelBindingContext {
                ModelMetadata = context.PropertyMetadata[descriptor.Name],
                ModelName     = prefix,
                ValueProvider = context.ValueProvider
            };
            IModelBinder propertyBinder = Binders.GetBinder(descriptor.PropertyType);
            object       value          = GetPropertyValue(controllerContext, propertyContext, descriptor, propertyBinder);
            SetProperty(controllerContext, context, descriptor, value);
        }
        return(model);
    }
        internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType)
        {
            IModelBinder elementBinder = Binders.GetBinder(elementType);

            // build up a list of items from the request
            List <object> modelList = new List <object>();

            for (int currentIndex = 0; ; currentIndex++)
            {
                string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);
                if (!DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, subIndexKey))
                {
                    // we ran out of elements to pull
                    break;
                }

                ModelBindingContext innerContext = new ModelBindingContext()
                {
                    ModelName      = subIndexKey,
                    ModelState     = bindingContext.ModelState,
                    ModelType      = elementType,
                    PropertyFilter = bindingContext.PropertyFilter,
                    ValueProvider  = bindingContext.ValueProvider
                };
                object thisElement = elementBinder.BindModel(controllerContext, innerContext);

                // we need to merge model errors up
                VerifyValueUsability(controllerContext, bindingContext.ModelState, subIndexKey, elementType, thisElement);
                modelList.Add(thisElement);
            }

            // if there weren't any elements at all in the request, just return
            if (modelList.Count == 0)
            {
                return(null);
            }

            // replace the original collection
            object collection = bindingContext.Model;

            CollectionHelpers.ReplaceCollection(elementType, collection, modelList);
            return(collection);
        }
Ejemplo n.º 25
0
        protected bool TryUpdateModel(object model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            var modelContext = new ModelBindingContext()
            {
                ModelMetadata =
                    ModelMetadataProviders.Current.GetMetadataForType((() => model), model.GetType()),
                ModelName      = null,
                ModelState     = ModelState,
                PropertyFilter = s => true,
                ValueProvider  = ValueProvider
            };

            Binders.GetBinder(model.GetType()).BindModel(ControllerContext, modelContext);
            return(ModelState.IsValid);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Tries to update a model that was created through reflection, e.g. is of type "object".
        /// </summary>
        /// <param name="modelType">Type of the entity.</param>
        /// <param name="model">The model.</param>
        /// <param name="prefix">The prefix.</param>
        /// <param name="includeProperties">The include properties.</param>
        /// <param name="valueProvider">The value provider.</param>
        /// <returns></returns>
        private bool TryUpdateReflectedModel(Type modelType, object model, string prefix, string[] includeProperties, IValueProvider valueProvider)
        {
            // code from https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/Controller.cs#L648
            // also see http://prideparrot.com/blog/archive/2012/6/gotchas_in_explicit_model_binding

            Predicate <string> propertyFilter = propertyName => includeProperties.Contains(propertyName);
            var binder = Binders.GetBinder(modelType);

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType),
                ModelName      = prefix,
                ModelState     = ModelState,
                PropertyFilter = propertyFilter,
                ValueProvider  = valueProvider
            };

            binder.BindModel(ControllerContext, bindingContext);
            return(ModelState.IsValid);
        }
    private object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType)
    {
        var collection    = (IList)bindingContext.Model;
        var elementBinder = Binders.GetBinder(elementType);
        var modelList     = new List <object>();

        for (var index = 0; index < collection.Count; index++)
        {
            var innerContext = new ModelBindingContext
            {
                ModelMetadata  = ModelMetadataProviders.Current.GetMetadataForType(() => collection[index], elementType),
                ModelName      = CreateSubIndexName(bindingContext.ModelName, index),
                ModelState     = bindingContext.ModelState,
                PropertyFilter = bindingContext.PropertyFilter,
                ValueProvider  = bindingContext.ValueProvider
            };

            modelList.Add(elementBinder.BindModel(controllerContext, innerContext));
        }

        return(modelList);
    }
        private object BindCollection(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object collection           = bindingContext.Model;
            Type   collectionMemberType = typeof(Object);

            if (collection.GetType().IsGenericType)
            {
                collectionMemberType =
                    collection.GetType().GetGenericArguments()[0];
            }
            int count = collection.CollectionGetCount();

            for (int index = 0; index < count; index++)
            {
                // Create a BindingContext for the collection member:
                ModelBindingContext innerContext = new ModelBindingContext();
                object member     = collection.CollectionGetItem(index);
                Type   memberType =
                    (member == null) ? collectionMemberType : member.GetType();
                innerContext.ModelMetadata =
                    ModelMetadataProviders.Current.GetMetadataForType(
                        delegate() { return(member); },
                        memberType);
                innerContext.ModelName =
                    String.Format("{0}[{1}]", bindingContext.ModelName, index);
                innerContext.ModelState     = bindingContext.ModelState;
                innerContext.PropertyFilter = bindingContext.PropertyFilter;
                innerContext.ValueProvider  = bindingContext.ValueProvider;

                // Bind the collection member:
                IModelBinder binder      = Binders.GetBinder(memberType);
                object       boundMember =
                    binder.BindModel(controllerContext, innerContext) ?? member;
                collection.CollectionSetItem(index, boundMember);
            }

            // Return the collection:
            return(collection);
        }
Ejemplo n.º 29
0
        /// <inheritdoc cref="DefaultModelBinder.BindProperty(ControllerContext, ModelBindingContext, PropertyDescriptor)" />
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            var dataMember = propertyDescriptor.Attributes.OfType <DataMemberAttribute>().FirstOrDefault();

            if (dataMember == null)
            {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);

                return;
            }

            var original = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);
            var alias    = CreateSubPropertyName(bindingContext.ModelName, dataMember.Name);

            if (!bindingContext.ValueProvider.ContainsPrefix(alias))
            {
                return;
            }

            var binder   = Binders.GetBinder(propertyDescriptor.PropertyType);
            var metadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];

            metadata.Model = propertyDescriptor.GetValue(bindingContext.Model);

            var innerBindingContext = new ModelBindingContext
            {
                ModelMetadata = metadata,
                ModelName     = alias,
                ModelState    = bindingContext.ModelState,
                ValueProvider = bindingContext.ValueProvider
            };

            var value = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, binder);

            propertyDescriptor.SetValue(bindingContext.ModelMetadata.Model, value);

            metadata.Model = value;
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Take the data in the form collection and overwrite changed values in the original data
        /// </summary>
        /// <param name="data">The original data (freshly obtained)</param>
        /// <param name="form">The editor form data as edited by the user</param>
        protected void Bind(object data, FormCollection form)
        {
            var binder = Binders.GetBinder(data.GetType());

            var bindingContext = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => data, data.GetType()),
                ModelState    = ModelState,
                ValueProvider = form
            };

            if (form.Count == 0)
            {
                log.WarnFormat("Attempt to save empty form on: " + Request.RawUrl);
            }
            else
            {
                // Empty all collections, since binding will not change a property for which there are no form values
                new ContentBindingPreparer().Visit(data);
            }

            binder.BindModel(ControllerContext, bindingContext);
        }