public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBinderUtil.ValidateBindingContext(bindingContext); ValueProviderResult vpResult = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName); // case 1: there was no <input ... /> element containing this data if (vpResult == null) { return false; } string base64string = (string)vpResult.ConvertTo(typeof(string)); // case 2: there was an <input ... /> element but it was left blank if (String.IsNullOrEmpty(base64string)) { return false; } // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary // then we need to remove these quotes put in place by the ToString() method. string realValue = base64string.Replace("\"", String.Empty); try { bindingContext.Model = ConvertByteArray(Convert.FromBase64String(realValue)); return true; } catch { // corrupt data - just ignore return false; } }
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBindingContext newBindingContext = bindingContext; IModelBinder binder = Providers.GetBinder(modelBindingExecutionContext, bindingContext); if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName) && bindingContext.ModelMetadata.IsComplexType) { // fallback to empty prefix? newBindingContext = new ModelBindingContext(bindingContext) { ModelName = String.Empty, ModelMetadata = bindingContext.ModelMetadata }; binder = Providers.GetBinder(modelBindingExecutionContext, newBindingContext); } if (binder != null) { bool boundSuccessfully = binder.BindModel(modelBindingExecutionContext, newBindingContext); if (boundSuccessfully) { // run validation newBindingContext.ValidationNode.Validate(modelBindingExecutionContext, parentNode:null); return true; } } return false; // something went wrong }
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBinderUtil.ValidateBindingContext(bindingContext); ValueProviderResult vpResult = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName, skipValidation: !bindingContext.ValidateRequest); if (vpResult == null) { return false; // no entry } object newModel; bindingContext.ModelState.SetModelValue(bindingContext.ModelName, vpResult); try { newModel = vpResult.ConvertTo(bindingContext.ModelType); } catch (Exception ex) { if (IsFormatException(ex)) { // there was a type conversion failure string errorString = ModelBinderErrorMessageProviders.TypeConversionErrorMessageProvider(modelBindingExecutionContext, bindingContext.ModelMetadata, vpResult.AttemptedValue); if (errorString != null) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorString); } } else { bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex); } return false; } ModelBinderUtil.ReplaceEmptyStringWithNull(bindingContext.ModelMetadata, ref newModel); bindingContext.Model = newModel; return true; }
// copies certain values that won't change between parent and child objects, // e.g. ValueProvider, ModelState public ModelBindingContext(ModelBindingContext bindingContext) { if (bindingContext != null) { ModelBinderProviders = bindingContext.ModelBinderProviders; ModelState = bindingContext.ModelState; ValueProvider = bindingContext.ValueProvider; ValidateRequest = bindingContext.ValidateRequest; } }
public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBinderUtil.ValidateBindingContext(bindingContext); if (bindingContext.UnvalidatedValueProvider.ContainsPrefix(bindingContext.ModelName)) { return CollectionModelBinderUtil.GetGenericBinder(typeof(IDictionary<,>), typeof(Dictionary<,>), typeof(DictionaryModelBinder<,>), bindingContext.ModelMetadata); } else { return null; } }
public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBinderUtil.ValidateBindingContext(bindingContext); if (bindingContext.ModelType == ModelType) { if (SuppressPrefixCheck || bindingContext.UnvalidatedValueProvider.ContainsPrefix(bindingContext.ModelName)) { return _modelBinderFactory(); } } return null; }
public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBinderUtil.ValidateBindingContext(bindingContext); if (!bindingContext.ModelMetadata.IsReadOnly && bindingContext.ModelType.IsArray && bindingContext.UnvalidatedValueProvider.ContainsPrefix(bindingContext.ModelName)) { Type elementType = bindingContext.ModelType.GetElementType(); return (IModelBinder)Activator.CreateInstance(typeof(ArrayModelBinder<>).MakeGenericType(elementType)); } return null; }
private ComplexModel CreateAndPopulateComplexModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, IEnumerable<ModelMetadata> propertyMetadatas) { // create a Complex Model and call into the Complex Model binder ComplexModel originalComplexModel = new ComplexModel(bindingContext.ModelMetadata, propertyMetadatas); ModelBindingContext complexModelBindingContext = new ModelBindingContext(bindingContext) { ModelMetadata = MetadataProvider.GetMetadataForType(() => originalComplexModel, typeof(ComplexModel)), ModelName = bindingContext.ModelName }; IModelBinder complexModelBinder = bindingContext.ModelBinderProviders.GetRequiredBinder(modelBindingExecutionContext, complexModelBindingContext); complexModelBinder.BindModel(modelBindingExecutionContext, complexModelBindingContext); return (ComplexModel)complexModelBindingContext.Model; }
public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBinderUtil.ValidateBindingContext(bindingContext); string keyFieldName = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, "key"); string valueFieldName = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, "value"); if (bindingContext.UnvalidatedValueProvider.ContainsPrefix(keyFieldName) && bindingContext.UnvalidatedValueProvider.ContainsPrefix(valueFieldName)) { return ModelBinderUtil.GetPossibleBinderInstance(bindingContext.ModelType, typeof(KeyValuePair<,>) /* supported model type */, typeof(KeyValuePairModelBinder<,>) /* binder type */); } else { // 'key' or 'value' missing return null; } }
public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBinderUtil.ValidateBindingContext(bindingContext); ValueProviderResult vpResult = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName, skipValidation: !bindingContext.ValidateRequest); if (vpResult == null) { return null; // no value to convert } if (!TypeDescriptor.GetConverter(bindingContext.ModelType).CanConvertFrom(typeof(string))) { return null; // this type cannot be converted } return new TypeConverterModelBinder(); }
public virtual bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { // Recursive method - prevent stack overflow. RuntimeHelpers.EnsureSufficientExecutionStack(); ModelBinderUtil.ValidateBindingContext(bindingContext); EnsureModel(modelBindingExecutionContext, bindingContext); IEnumerable<ModelMetadata> propertyMetadatas = GetMetadataForProperties(modelBindingExecutionContext, bindingContext); ComplexModel complexModel = CreateAndPopulateComplexModel(modelBindingExecutionContext, bindingContext, propertyMetadatas); // post-processing, e.g. property setters and hooking up validation ProcessComplexModel(modelBindingExecutionContext, bindingContext, complexModel); bindingContext.ValidationNode.ValidateAllProperties = true; // complex models require full validation return true; }
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { //var valueProvider = bindingContext.ValueProvider; //int x = (int)valueProvider.GetValue("X").ConvertTo(typeof(int)); //int y = (int)valueProvider.GetValue("Y").ConvertTo(typeof(int)); //if (!bindingContext.FallbackToEmptyPrefix) // return false; //bindingContext = new ModelBindingContext //{ // ModelMetadata = bindingContext.ModelMetadata, // ModelState = bindingContext.ModelState, // ValueProvider = bindingContext.ValueProvider //}; return true; }
public ModelBinderWrapper(object model = null) { modelBinder = new DefaultModelBinder(); modelState = new ModelStateDictionary(); var contextBase = new HttpContextWrapper(HttpContext.Current); executingContext = new ModelBindingExecutionContext(contextBase, modelState); bindingContext = new ModelBindingContext(); bindingContext.ValueProvider = new FormValueProvider(executingContext); if (model != null) { setModel(model); BindModel(); } }
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { var request = new AspNetRequest(modelBindingExecutionContext.HttpContext.Request); var binder = BinderCollection.FindBinderFor(bindingContext.ModelName, bindingContext.ModelType, request, null); if (binder == null) return false; var bindingResult = binder.Bind(bindingContext.ModelName, bindingContext.ModelType, request, false, null); if(!bindingResult.BoundSuccessfully) { foreach (var error in bindingResult.BindingErrors) modelBindingExecutionContext.ModelState.AddModelError(error.Key, error.Message); } return bindingResult.BoundSuccessfully; }
public object BindModel(ControllerContext controllerContext, System.Web.ModelBinding.ModelBindingContext bindingContext) { // get the Cart from the session Cart cart = null; if (controllerContext.HttpContext.Session != null) { cart = (Cart)controllerContext.HttpContext.Session[sessionKey]; } // create the Cart if there wasn't one in the session data if (cart == null) { cart = new Cart(); if (controllerContext.HttpContext.Session != null) { controllerContext.HttpContext.Session[sessionKey] = cart; } } // return the cart return(cart); }
public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { ModelBinderUtil.ValidateBindingContext(bindingContext); Type[] typeArguments = null; if (ModelType.IsInterface) { Type matchingClosedInterface = TypeHelpers.ExtractGenericInterface(bindingContext.ModelType, ModelType); if (matchingClosedInterface != null) { typeArguments = matchingClosedInterface.GetGenericArguments(); } } else { typeArguments = TypeHelpers.GetTypeArgumentsIfMatch(bindingContext.ModelType, ModelType); } if (typeArguments != null) { if (SuppressPrefixCheck || bindingContext.UnvalidatedValueProvider.ContainsPrefix(bindingContext.ModelName)) { return _modelBinderFactory(typeArguments); } } return null; }
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { return true; }
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, WebFormsModelBindingContext bindingContext) { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); bindingContext.Model = BindModelImpl(valueProviderResult != null ? valueProviderResult.AttemptedValue : null); return bindingContext.Model != null; }
protected virtual object CreateModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { // If the Activator throws an exception, we want to propagate it back up the call stack, since the application // developer should know that this was an invalid type to try to bind to. return SecurityUtils.SecureCreateInstance(bindingContext.ModelType); }
public override IWebFormsModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, WebFormsModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(DbGeography)) return new DbGeographyModelBinder(); return null; }
public object BindParameter(ParameterInfo parameter) { var name = parameter.Name; bool validateRequest; var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType((Func<object>)null, parameter.ParameterType); var valueProvider = GetCustomValueProvider(parameter, ref name, out validateRequest); var context = new ModelBindingContext { ModelMetadata = modelMetadata, ValueProvider = valueProvider, ModelName = name }; var binder = ModelBinders.Binders[parameter.ParameterType] ?? ModelBinders.Binders.DefaultBinder; return binder.BindModel(_executionContext, context) ? context.Model : null; }
protected virtual void SetProperty(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelResult complexModelResult) { PropertyDescriptor propertyDescriptor = TypeDescriptorHelper.Get(bindingContext.ModelType).GetProperties().Find(propertyMetadata.PropertyName, true /* ignoreCase */); if (propertyDescriptor == null || propertyDescriptor.IsReadOnly) { return; // nothing to do } object value = complexModelResult.Model ?? GetPropertyDefaultValue(propertyDescriptor); propertyMetadata.Model = value; // 'Required' validators need to run first so that we can provide useful error messages if // the property setters throw, e.g. if we're setting entity keys to null. See comments in // DefaultModelBinder.SetProperty() for more information. if (value == null) { string modelStateKey = complexModelResult.ValidationNode.ModelStateKey; if (bindingContext.ModelState.IsValidField(modelStateKey)) { ModelValidator requiredValidator = ModelValidatorProviders.Providers.GetValidators(propertyMetadata, modelBindingExecutionContext).Where(v => v.IsRequired).FirstOrDefault(); if (requiredValidator != null) { foreach (ModelValidationResult validationResult in requiredValidator.Validate(bindingContext.Model)) { bindingContext.ModelState.AddModelError(modelStateKey, validationResult.Message); } } } } if (value != null || TypeHelpers.TypeAllowsNullValue(propertyDescriptor.PropertyType)) { try { propertyDescriptor.SetValue(bindingContext.Model, value); } catch (Exception ex) { // don't display a duplicate error message if a binding error has already occurred for this field string modelStateKey = complexModelResult.ValidationNode.ModelStateKey; if (bindingContext.ModelState.IsValidField(modelStateKey)) { bindingContext.ModelState.AddModelError(modelStateKey, ex); } } } else { // trying to set a non-nullable value type to null, need to make sure there's a message string modelStateKey = complexModelResult.ValidationNode.ModelStateKey; if (bindingContext.ModelState.IsValidField(modelStateKey)) { complexModelResult.ValidationNode.Validated += CreateNullCheckFailedHandler(modelBindingExecutionContext, propertyMetadata, value); } } }
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { if (Regex.IsMatch((string)bindingContext.Model, "<>")) { throw new Exception(); } return true; }
protected virtual IEnumerable<ModelMetadata> GetMetadataForProperties(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { // keep a set of the required properties so that we can cross-reference bound properties later HashSet<string> requiredProperties; HashSet<string> skipProperties; GetRequiredPropertiesCollection(bindingContext.ModelType, out requiredProperties, out skipProperties); return from propertyMetadata in bindingContext.ModelMetadata.Properties let propertyName = propertyMetadata.PropertyName let shouldUpdateProperty = requiredProperties.Contains(propertyName) || !skipProperties.Contains(propertyName) where shouldUpdateProperty && CanUpdateProperty(propertyMetadata) select propertyMetadata; }
protected virtual void EnsureModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { if (bindingContext.Model == null) { bindingContext.ModelMetadata.Model = CreateModel(modelBindingExecutionContext, bindingContext); } }
/// <summary> /// Evaluates the method parameters using model binding. /// </summary> /// <param name="dataSourceOperation">The datasource operation for which parameters are being evaluated.</param> /// <param name="modelDataSourceMethod">The ModelDataSourceMethod object for which the Parameter collection is being evaluated. The MethodInfo property should already be set on this object.</param> /// <param name="controlValues">The values from the data bound control.</param> /// <param name="isPageLoadComplete">This must be set to true only when this method is called in Page's LoadComplete event handler /// to evaluate the select method parameters that use custom value providers so that we can identify any changes /// to those and mark the data-bound control for data binding if necessary.</param> protected virtual void EvaluateMethodParameters(DataSourceOperation dataSourceOperation, ModelDataSourceMethod modelDataSourceMethod, IDictionary controlValues, bool isPageLoadComplete) { Debug.Assert(_owner.DataControl.Page != null); Debug.Assert(_owner.DataControl.TemplateControl != null); MethodInfo actionMethod = modelDataSourceMethod.MethodInfo; IModelBinder binder = ModelBinders.Binders.DefaultBinder; IValueProvider dataBoundControlValueProvider = GetValueProviderFromDictionary(controlValues); ModelBindingExecutionContext modelBindingExecutionContext = _owner.DataControl.Page.ModelBindingExecutionContext; Control previousDataControl = null; if (BinaryCompatibility.Current.TargetsAtLeastFramework46) { // DevDiv 1087698: a child control overwrites its parent controls's modelBindingExecutionContext, // which may cause a problem for the parent control to find control by controlId. Control dataControl = modelBindingExecutionContext.TryGetService<Control>(); if (dataControl != _owner.DataControl) { previousDataControl = dataControl; } } //This is used by ControlValueProvider later. modelBindingExecutionContext.PublishService<Control>(_owner.DataControl); //This is done for the TryUpdateModel to work inside a Data Method. if (dataSourceOperation != DataSourceOperation.Select) { _owner.DataControl.Page.SetActiveValueProvider(dataBoundControlValueProvider); } var methodParameters = actionMethod.GetParameters(); ParameterInfo lastParameter = null; if (methodParameters.Length > 0) { lastParameter = methodParameters[methodParameters.Length - 1]; } foreach (ParameterInfo parameterInfo in methodParameters) { object value = null; string modelName = parameterInfo.Name; if (parameterInfo.ParameterType == typeof(ModelMethodContext)) { //ModelMethodContext is a special parameter we pass in for enabling developer to call //TryUpdateModel when Select/Update/Delete/InsertMethods are on a custom class. value = new ModelMethodContext(_owner.DataControl.Page); } //Do not attempt model binding the out parameters else if (!parameterInfo.IsOut) { bool validateRequest; IValueProvider customValueProvider = GetCustomValueProvider(modelBindingExecutionContext, parameterInfo, ref modelName, out validateRequest); //When we are evaluating the parameter at the time of page load, we do not want to populate the actual ModelState //because there will be another evaluation at data-binding causing duplicate errors if model validation fails. ModelStateDictionary modelState = isPageLoadComplete ? new ModelStateDictionary() : _owner.DataControl.Page.ModelState; ModelBindingContext bindingContext = new ModelBindingContext() { ModelBinderProviders = ModelBinderProviders.Providers, ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterInfo.ParameterType), ModelState = modelState, ModelName = modelName, ValueProvider = customValueProvider, ValidateRequest = validateRequest }; //Select parameters that take custom values providers are tracked by ViewState so that //we can detect any changes from previous page request and mark the data bound control for data binding if necessary. if (dataSourceOperation == DataSourceOperation.Select && customValueProvider != null && parameterInfo.ParameterType.IsSerializable) { if (!SelectParameters.ContainsKey(parameterInfo.Name)) { SelectParameters.Add(parameterInfo.Name, new MethodParameterValue()); } if (binder.BindModel(modelBindingExecutionContext, bindingContext)) { value = bindingContext.Model; } SelectParameters[parameterInfo.Name].UpdateValue(value); } else { if (isPageLoadComplete) { Debug.Assert(dataSourceOperation == DataSourceOperation.Select, "Only Select Operation should have been done immediately after page load"); //When this method is called as part of Page's LoadComplete event handler we do not have values in defaultValueProvider //(i.e., values from DataBoundControl), so we need not evaluate the parameters values. continue; } if (customValueProvider == null) { bindingContext.ValueProvider = dataBoundControlValueProvider; } if (binder.BindModel(modelBindingExecutionContext, bindingContext)) { value = bindingContext.Model; } } // We set the CancellationToken after EvaluateMethodParameters(). // We don't want to set a null value to a CancellationToken variable. if (parameterInfo == lastParameter && typeof(CancellationToken) == parameterInfo.ParameterType && value == null) { value = CancellationToken.None; } if (!isPageLoadComplete) { ValidateParameterValue(parameterInfo, value, actionMethod); } } modelDataSourceMethod.Parameters.Add(parameterInfo.Name, value); } if (previousDataControl != null) { modelBindingExecutionContext.PublishService<Control>(previousDataControl); } }
public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { return (from provider in _providers let binder = provider.GetBinder(modelBindingExecutionContext, bindingContext) where binder != null select binder).FirstOrDefault(); }
public override IWebFormsModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, WebFormsModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(DbGeography)) { return(new DbGeographyModelBinder()); } return(null); }
public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, System.Web.ModelBinding.ModelBindingContext bindingContext) { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); bindingContext.Model = BindModelImpl(valueProviderResult != null ? valueProviderResult.AttemptedValue : null); return(bindingContext.Model != null); }
internal void ProcessComplexModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, ComplexModel complexModel) { HashSet<string> requiredProperties; HashSet<string> skipProperties; GetRequiredPropertiesCollection(bindingContext.ModelType, out requiredProperties, out skipProperties); // Are all of the required fields accounted for? HashSet<string> missingRequiredProperties = new HashSet<string>(requiredProperties); missingRequiredProperties.ExceptWith(complexModel.Results.Select(r => r.Key.PropertyName)); string missingPropertyName = missingRequiredProperties.FirstOrDefault(); if (missingPropertyName != null) { string fullPropertyKey = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, missingPropertyName); throw Error.BindingBehavior_ValueNotFound(fullPropertyKey); } // for each property that was bound, call the setter, recording exceptions as necessary foreach (var entry in complexModel.Results) { ModelMetadata propertyMetadata = entry.Key; ComplexModelResult complexModelResult = entry.Value; if (complexModelResult != null) { SetProperty(modelBindingExecutionContext, bindingContext, propertyMetadata, complexModelResult); bindingContext.ValidationNode.ChildNodes.Add(complexModelResult.ValidationNode); } } }
public override System.Web.ModelBinding.IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, System.Web.ModelBinding.ModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(DbGeography)) { return(new DbGeographyModelBinder()); } return(null); }
public override IModelBinder GetBinder(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(string)) { return new MyBinder(); } return null; }