Exemplo n.º 1
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            ModelBindingHelper.ValidateBindingContext(bindingContext);

            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(
                bindingContext.ModelName
                );

            if (valueProviderResult == null)
            {
                return(false); // no entry
            }

            // Provider should have verified this before creating
            Contract.Assert(TypeHelper.HasStringConverter(bindingContext.ModelType));

            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(
                        actionContext,
                        bindingContext.ModelMetadata,
                        valueProviderResult.AttemptedValue
                        );
                    if (errorString != null)
                    {
                        bindingContext.ModelState.AddModelError(
                            bindingContext.ModelName,
                            errorString
                            );
                    }
                }
                else
                {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
                }
                return(false);
            }

            ModelBindingHelper.ReplaceEmptyStringWithNull(
                bindingContext.ModelMetadata,
                ref newModel
                );
            bindingContext.Model = newModel;
            return(true);
        }
Exemplo n.º 2
0
        public void TypeConversionErrorMessageProvider_DefaultValue()
        {
            // Arrange
            ModelMetadata metadata = new ModelMetadata(new Mock <ModelMetadataProvider>().Object, null, null, typeof(int), "SomePropertyName");

            // Act
            string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(null, metadata, "some incoming value");

            // Assert
            Assert.Equal("The value 'some incoming value' is not valid for SomePropertyName.", errorString);
        }