// Called when the property setter null check failed, allows us to add our own error message to ModelState. internal static EventHandler <ModelValidatedEventArgs> CreateNullCheckFailedHandler( ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue ) { return((sender, e) => { ModelValidationNode validationNode = (ModelValidationNode)sender; ModelStateDictionary modelState = e.ControllerContext.Controller.ViewData.ModelState; if (modelState.IsValidField(validationNode.ModelStateKey)) { string errorMessage = ModelBinderConfig.ValueRequiredErrorMessageProvider( controllerContext, modelMetadata, incomingValue ); if (errorMessage != null) { modelState.AddModelError(validationNode.ModelStateKey, errorMessage); } } }); }
public bool BindModel( ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext ) { ModelBinderUtil.ValidateBindingContext(bindingContext); ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue( bindingContext.ModelName ); if (valueProviderResult == null) { return(false); // no entry } object newModel; bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); try { newModel = valueProviderResult.ConvertTo(bindingContext.ModelType); } catch (Exception ex) { if (IsFormatException(ex)) { // there was a type conversion failure string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider( controllerContext, bindingContext.ModelMetadata, valueProviderResult.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); }