Пример #1
0
        /// <inheritdoc />
        public async Task<ModelBindingResult> BindModelAsync([NotNull] ModelBindingContext bindingContext)
        {
            object value;
            if (bindingContext.ModelType == typeof(IFormFile))
            {
                var postedFiles = await GetFormFilesAsync(bindingContext);
                value = postedFiles.FirstOrDefault();
            }
            else if (typeof(IEnumerable<IFormFile>).IsAssignableFrom(bindingContext.ModelType))
            {
                var postedFiles = await GetFormFilesAsync(bindingContext);
                value = ModelBindingHelper.ConvertValuesToCollectionType(bindingContext.ModelType, postedFiles);
            }
            else
            {
                // This binder does not support the requested type.
                return null;
            }

            ModelValidationNode validationNode = null;
            if (value != null)
            {
                validationNode =
                    new ModelValidationNode(bindingContext.ModelName, bindingContext.ModelMetadata, value);

                var valueProviderResult = new ValueProviderResult(rawValue: value);
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            }

            return new ModelBindingResult(
                value,
                bindingContext.ModelName,
                isModelSet: value != null,
                validationNode: validationNode);
        }
Пример #2
0
        public void Construct_With_Array()
        {
            // Arrange & Act
            var result = new ValueProviderResult(new string[] { "Hi", "There" });

            // Assert
            Assert.Equal(2, result.Length);
            Assert.Equal(new string[] { "Hi", "There" }, result.Values);
            Assert.Equal("Hi", result.FirstValue);
            Assert.NotEqual(ValueProviderResult.None, result);
            Assert.Equal("Hi,There", (string)result);
            Assert.Equal(new string[] { "Hi", "There" }, (string[])result);
        }
Пример #3
0
        public void Construct_With_NullArray()
        {
            // Arrange & Act
            var result = new ValueProviderResult((string[])null);

            // Assert
            Assert.Equal(0, result.Length);
            Assert.Empty(result.Values);
            Assert.Null(result.FirstValue);
            Assert.Equal(ValueProviderResult.None, result);
            Assert.Null((string)result);
            Assert.Null((string[])result);
        }
        /// <inheritdoc />
        public override Task<ValueProviderResult> GetValueAsync([NotNull] string key)
        {
            object value;
            ValueProviderResult result;
            if (_values.TryGetValue(key, out value))
            {
                var attemptedValue = value != null ? value.ToString() : null;
                result = new ValueProviderResult(value, attemptedValue, CultureInfo.InvariantCulture);
            }
            else
            {
                result = null;
            }

            return Task.FromResult(result);
        }
Пример #5
0
        /// <inheritdoc />
        public async Task <ModelBindingResult> BindModelAsync([NotNull] ModelBindingContext bindingContext)
        {
            object value;

            if (bindingContext.ModelType == typeof(IFormFile))
            {
                var postedFiles = await GetFormFilesAsync(bindingContext);

                value = postedFiles.FirstOrDefault();
            }
            else if (typeof(IEnumerable <IFormFile>).IsAssignableFrom(bindingContext.ModelType))
            {
                var postedFiles = await GetFormFilesAsync(bindingContext);

                value = ModelBindingHelper.ConvertValuesToCollectionType(bindingContext.ModelType, postedFiles);
            }
            else
            {
                // This binder does not support the requested type.
                return(null);
            }

            ModelValidationNode validationNode = null;

            if (value != null)
            {
                validationNode =
                    new ModelValidationNode(bindingContext.ModelName, bindingContext.ModelMetadata, value);

                var valueProviderResult = new ValueProviderResult(rawValue: value);
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            }

            return(new ModelBindingResult(
                       value,
                       bindingContext.ModelName,
                       isModelSet: value != null,
                       validationNode: validationNode));
        }
        public virtual async Task<ValueProviderResult> GetValueAsync([NotNull] string key)
        {
            var collection = await GetValueCollectionAsync();
            var values = collection.GetValues(key);

            ValueProviderResult result;
            if (values == null)
            {
                result = null;
            }
            else if (values.Count == 1)
            {
                var value = (string)values[0];
                result = new ValueProviderResult(value, value, _culture);
            }
            else
            {
                result = new ValueProviderResult(values, _values.Get(key), _culture);
            }

            return result;
        }
Пример #7
0
        public virtual async Task <ValueProviderResult> GetValueAsync([NotNull] string key)
        {
            var collection = await GetValueCollectionAsync();

            var values = collection.GetValues(key);

            ValueProviderResult result;

            if (values == null)
            {
                result = null;
            }
            else if (values.Count == 1)
            {
                var value = (string)values[0];
                result = new ValueProviderResult(value, value, _culture);
            }
            else
            {
                result = new ValueProviderResult(values, _values.Get(key), _culture);
            }

            return(result);
        }
Пример #8
0
        public void ListBoxInTemplate_GetsModelStateEntry()
        {
            // Arrange
            var expectedHtml = GetExpectedSelectElementWithPrefix(
                SelectSources.ModelStateEntryWithPrefix,
                allowMultiple: true);

            var entryResult = new ValueProviderResult(
                SelectSources.ModelStateEntry,
                SelectSources.ModelStateEntry.ToString(),
                culture: null);
            var entryResultWithPrefix = new ValueProviderResult(
                SelectSources.ModelStateEntryWithPrefix,
                SelectSources.ModelStateEntryWithPrefix.ToString(),
                culture: null);
            var modelState = new ModelStateDictionary
            {
                ["Property1"] = new ModelState { Value = entryResult },
                ["Prefix.Property1"] = new ModelState { Value = entryResultWithPrefix },
            };

            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var viewData = new ViewDataDictionary<ModelContainingListOfSources>(provider, modelState)
            {
                ["Property1"] = new[] { SelectSources.ViewDataEntry },
                ["Prefix.Property1"] = new[] { SelectSources.ViewDataEntryWithPrefix },
                ["Prefix"] = new ModelContainingListOfSources { Property1 = { SelectSources.PropertyOfViewDataEntry } },
            };
            viewData.Model = new ModelContainingListOfSources { Property1 = { SelectSources.PropertyOfModel } };
            viewData.TemplateInfo.HtmlFieldPrefix = "Prefix";

            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
            helper.ViewContext.ClientValidationEnabled = false;

            // Act
            var html = helper.ListBox("Property1", SourcesSelectList, htmlAttributes: null);

            // Assert
            Assert.Equal(expectedHtml, html.ToString());
        }
        public void CheckBoxForWithNullContainer_TreatsBooleanAsFalse()
        {
            // Arrange
            var expected = @"<input id=""Property1"" name=""Property1"" type=""checkbox"" value=""true"" />" +
                           @"<input name=""Property1"" type=""hidden"" value=""false"" />";
            var viewData = GetTestModelViewData();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
            var valueProviderResult = new ValueProviderResult("false", "false", CultureInfo.InvariantCulture);
            viewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBoxFor(m => m.Property1);

            // Assert
            Assert.Equal(expected, html.ToString());
        }
Пример #10
0
        public void Enumerator_WithArray()
        {
            // Arrange
            var result = new ValueProviderResult(new string[] { "Hi", "There" });

            // Act & Assert
            Assert.Equal<string>(new string[] { "Hi", "There" }, result);
        }
Пример #11
0
        public void Operator_NotEquals(ValueProviderResult x, ValueProviderResult y, bool expected)
        {
            // Arrange
            var result = x != y;

            // Act & Assert
            Assert.NotEqual(expected, result);
        }
Пример #12
0
        public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, string expectedChecked)
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input {0}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            expected = string.Format(expected, expectedChecked);

            var viewData = GetTestModelViewData();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
            var valueProviderResult =
                new ValueProviderResult(attemptedValue, attemptedValue, CultureInfo.InvariantCulture);
            viewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Пример #13
0
        public void CheckBoxUsesAttemptedValueFromModelState()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Boolean field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var valueProviderResult = new ValueProviderResult("false", "false", CultureInfo.InvariantCulture);
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            helper.ViewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Пример #14
0
        public void CheckBoxUsesAttemptedValueFromModelState()
        {
            // Arrange
            var expected = @"<input id=""Property1"" name=""Property1"" type=""checkbox"" value=""true"" />" +
                           @"<input name=""Property1"" type=""hidden"" value=""false"" />";
            var valueProviderResult = new ValueProviderResult("false", "false", CultureInfo.InvariantCulture);
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            helper.ViewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, html.ToString());
        }
Пример #15
0
        public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, string expectedChecked)
        {
            // Arrange
            var expected = @"<input {0}id=""Property1"" name=""Property1"" type=""checkbox"" value=""true"" />" +
                           @"<input name=""Property1"" type=""hidden"" value=""false"" />";
            expected = string.Format(expected, expectedChecked);

            var viewData = GetTestModelViewData();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
            var valueProviderResult =
                new ValueProviderResult(attemptedValue, attemptedValue, CultureInfo.InvariantCulture);
            viewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBoxFor(m => m.Property1);

            // Assert
            Assert.Equal(expected, html.ToString());
        }
Пример #16
0
        /// <inheritdoc />
        protected async override Task<ModelBindingResult> BindModelCoreAsync(
            [NotNull] ModelBindingContext bindingContext)
        {
            // For compatibility with MVC 5.0 for top level object we want to consider an empty key instead of
            // the parameter name/a custom name. In all other cases (like when binding body to a property) we
            // consider the entire ModelName as a prefix.
            var modelBindingKey = bindingContext.IsTopLevelObject ? string.Empty : bindingContext.ModelName;

            var httpContext = bindingContext.OperationBindingContext.HttpContext;

            var formatterContext = new InputFormatterContext(
                httpContext,
                bindingContext.ModelState,
                bindingContext.ModelType);
            var formatters = bindingContext.OperationBindingContext.InputFormatters;
            var formatter = formatters.FirstOrDefault(f => f.CanRead(formatterContext));

            if (formatter == null)
            {
                var unsupportedContentType = Resources.FormatUnsupportedContentType(
                    bindingContext.OperationBindingContext.HttpContext.Request.ContentType);
                bindingContext.ModelState.AddModelError(modelBindingKey, unsupportedContentType);

                // This model binder is the only handler for the Body binding source and it cannot run twice. Always
                // tell the model binding system to skip other model binders and never to fall back i.e. indicate a
                // fatal error.
                return new ModelBindingResult(modelBindingKey);
            }

            try
            {
                var previousCount = bindingContext.ModelState.ErrorCount;
                var model = await formatter.ReadAsync(formatterContext);

                if (bindingContext.ModelState.ErrorCount != previousCount)
                {
                    // Formatter added an error. Do not use the model it returned. As above, tell the model binding
                    // system to skip other model binders and never to fall back.
                    return new ModelBindingResult(modelBindingKey);
                }

                var valueProviderResult = new ValueProviderResult(rawValue: model);
                bindingContext.ModelState.SetModelValue(modelBindingKey, valueProviderResult);

                var validationNode = new ModelValidationNode(modelBindingKey, bindingContext.ModelMetadata, model)
                {
                    ValidateAllProperties = true
                };

                return new ModelBindingResult(
                    model,
                    key: modelBindingKey,
                    isModelSet: true,
                    validationNode: validationNode);
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(modelBindingKey, ex);

                // This model binder is the only handler for the Body binding source and it cannot run twice. Always
                // tell the model binding system to skip other model binders and never to fall back i.e. indicate a
                // fatal error.
                return new ModelBindingResult(modelBindingKey);
            }
        }
Пример #17
0
 public void SetModelValue([NotNull] string key, [NotNull] ValueProviderResult value)
 {
     GetModelStateForKey(key).Value = value;
 }
Пример #18
0
        public void DropDownListNotInTemplate_GetsModelStateEntry()
        {
            // Arrange
            var expectedHtml = GetExpectedSelectElement(SelectSources.ModelStateEntry, allowMultiple: false);

            var entryResult = new ValueProviderResult(
                SelectSources.ModelStateEntry,
                SelectSources.ModelStateEntry.ToString(),
                culture: null);
            var entryResultWithPrefix = new ValueProviderResult(
                SelectSources.ModelStateEntryWithPrefix,
                SelectSources.ModelStateEntryWithPrefix.ToString(),
                culture: null);
            var modelState = new ModelStateDictionary
            {
                ["Property1"] = new ModelState { Value = entryResult },
                ["Prefix.Property1"] = new ModelState { Value = entryResultWithPrefix },
            };

            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var viewData = new ViewDataDictionary<ModelContainingSources>(provider, modelState)
            {
                ["Property1"] = SelectSources.ViewDataEntry,
                ["Prefix.Property1"] = SelectSources.ViewDataEntryWithPrefix,
                ["Prefix"] = new ModelContainingSources { Property1 = SelectSources.PropertyOfViewDataEntry },
            };
            viewData.Model = new ModelContainingSources { Property1 = SelectSources.PropertyOfModel };

            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
            helper.ViewContext.ClientValidationEnabled = false;

            // Act
            var html = helper.DropDownList("Property1", SourcesSelectList, optionLabel: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(html));
        }
        public void CheckBoxUsesAttemptedValueFromModelState()
        {
            // Arrange
            var expected =
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Boolean field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var valueProviderResult = new ValueProviderResult("false", "false", CultureInfo.InvariantCulture);
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            helper.ViewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, html.ToString());
        }
        public void CheckBoxForWithNullContainer_TreatsBooleanAsFalse()
        {
            // Arrange
            var expected =
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var viewData = GetTestModelViewData();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
            var valueProviderResult = new ValueProviderResult("false", "false", CultureInfo.InvariantCulture);
            viewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, html.ToString());
        }
Пример #21
0
        public void Enumerator_WithString()
        {
            // Arrange
            var result = new ValueProviderResult("Hi There");

            // Act & Assert
            Assert.Equal<string>(new string[] { "Hi There", }, result);
        }
        public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, string expectedChecked)
        {
            // Arrange
            var expected =
                @"<input {0}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            expected = string.Format(expected, expectedChecked);

            var viewData = GetTestModelViewData();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
            var valueProviderResult =
                new ValueProviderResult(attemptedValue, attemptedValue, CultureInfo.InvariantCulture);
            viewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, html.ToString());
        }
 public Task<ValueProviderResult> GetValueAsync(string key)
 {
     var value = "custom-value-provider-value";
     var result = new ValueProviderResult(value, value, CultureInfo.CurrentCulture);
     return Task.FromResult(result);
 }
Пример #24
0
        /// <inheritdoc />
        protected async override Task <ModelBindingResult> BindModelCoreAsync(
            [NotNull] ModelBindingContext bindingContext)
        {
            // For compatibility with MVC 5.0 for top level object we want to consider an empty key instead of
            // the parameter name/a custom name. In all other cases (like when binding body to a property) we
            // consider the entire ModelName as a prefix.
            var modelBindingKey = bindingContext.IsTopLevelObject ? string.Empty : bindingContext.ModelName;

            var httpContext = bindingContext.OperationBindingContext.HttpContext;

            var formatterContext = new InputFormatterContext(
                httpContext,
                bindingContext.ModelState,
                bindingContext.ModelType);
            var formatters = bindingContext.OperationBindingContext.InputFormatters;
            var formatter  = formatters.FirstOrDefault(f => f.CanRead(formatterContext));

            if (formatter == null)
            {
                var unsupportedContentType = Resources.FormatUnsupportedContentType(
                    bindingContext.OperationBindingContext.HttpContext.Request.ContentType);
                bindingContext.ModelState.AddModelError(modelBindingKey, unsupportedContentType);

                // This model binder is the only handler for the Body binding source and it cannot run twice. Always
                // tell the model binding system to skip other model binders and never to fall back i.e. indicate a
                // fatal error.
                return(new ModelBindingResult(modelBindingKey));
            }

            try
            {
                var previousCount = bindingContext.ModelState.ErrorCount;
                var model         = await formatter.ReadAsync(formatterContext);

                if (bindingContext.ModelState.ErrorCount != previousCount)
                {
                    // Formatter added an error. Do not use the model it returned. As above, tell the model binding
                    // system to skip other model binders and never to fall back.
                    return(new ModelBindingResult(modelBindingKey));
                }

                var valueProviderResult = new ValueProviderResult(rawValue: model);
                bindingContext.ModelState.SetModelValue(modelBindingKey, valueProviderResult);

                var validationNode = new ModelValidationNode(modelBindingKey, bindingContext.ModelMetadata, model)
                {
                    ValidateAllProperties = true
                };

                return(new ModelBindingResult(
                           model,
                           key: modelBindingKey,
                           isModelSet: true,
                           validationNode: validationNode));
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(modelBindingKey, ex);

                // This model binder is the only handler for the Body binding source and it cannot run twice. Always
                // tell the model binding system to skip other model binders and never to fall back i.e. indicate a
                // fatal error.
                return(new ModelBindingResult(modelBindingKey));
            }
        }