Skip to content

Fix MVC form data binding localization #43182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Aug 15, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public void Configure(MvcOptions options)
options.OutputFormatters.Add(jsonOutputFormatter);

// Set up ValueProviders
options.ValueProviderFactories.Add(new FormValueProviderFactory());
options.ValueProviderFactories.Add(new FormValueProviderFactory(options));
options.ValueProviderFactories.Add(new RouteValueProviderFactory());
options.ValueProviderFactories.Add(new QueryStringValueProviderFactory());
options.ValueProviderFactories.Add(new JQueryFormValueProviderFactory());
Expand Down
12 changes: 12 additions & 0 deletions src/Mvc/Mvc.Core/src/ModelBinding/FormModelBindingHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Mvc.ModelBinding;

internal static class FormModelBindingHelper
{
public const string CultureInvariantFieldName = "__Invariant";

public static bool InputTypeUsesCultureInvariantFormatting(string? inputType)
=> inputType is "number" or "range";
}
29 changes: 27 additions & 2 deletions src/Mvc/Mvc.Core/src/ModelBinding/FormValueProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding;
public class FormValueProvider : BindingSourceValueProvider, IEnumerableValueProvider
{
private readonly IFormCollection _values;
private readonly HashSet<string?>? _invariantValueKeys;
private PrefixContainer? _prefixContainer;

/// <summary>
Expand All @@ -22,10 +23,12 @@ public class FormValueProvider : BindingSourceValueProvider, IEnumerableValuePro
/// <param name="bindingSource">The <see cref="BindingSource"/> for the data.</param>
/// <param name="values">The key value pairs to wrap.</param>
/// <param name="culture">The culture to return with ValueProviderResult instances.</param>
/// <param name="options">The <see cref="MvcOptions"/> options.</param>
public FormValueProvider(
BindingSource bindingSource,
IFormCollection values,
CultureInfo? culture)
CultureInfo? culture,
MvcOptions? options)
: base(bindingSource)
{
if (bindingSource == null)
Expand All @@ -39,9 +42,30 @@ public FormValueProvider(
}

_values = values;

var suppressCultureInvariantFormModelBinding = options?.SuppressCultureInvariantFormModelBinding == true;
if (!suppressCultureInvariantFormModelBinding && _values.TryGetValue(FormModelBindingHelper.CultureInvariantFieldName, out var invariantKeys))
{
_invariantValueKeys = new(invariantKeys, StringComparer.OrdinalIgnoreCase);
}

Culture = culture;
}

/// <summary>
/// Creates a value provider for <see cref="IFormCollection"/>.
/// </summary>
/// <param name="bindingSource">The <see cref="BindingSource"/> for the data.</param>
/// <param name="values">The key value pairs to wrap.</param>
/// <param name="culture">The culture to return with ValueProviderResult instances.</param>
public FormValueProvider(
BindingSource bindingSource,
IFormCollection values,
CultureInfo? culture)
: this(bindingSource, values, culture, options: null)
{
}

/// <summary>
/// The culture to use.
/// </summary>
Expand Down Expand Up @@ -104,7 +128,8 @@ public override ValueProviderResult GetValue(string key)
}
else
{
return new ValueProviderResult(values, Culture);
var culture = _invariantValueKeys?.Contains(key) == true ? CultureInfo.InvariantCulture : Culture;
return new ValueProviderResult(values, culture);
}
}
}
26 changes: 23 additions & 3 deletions src/Mvc/Mvc.Core/src/ModelBinding/FormValueProviderFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,25 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding;
/// </summary>
public class FormValueProviderFactory : IValueProviderFactory
{
private readonly MvcOptions? _options;

/// <summary>
/// Creates a new <see cref="FormValueProviderFactory"/>.
/// </summary>
/// <param name="options">The <see cref="MvcOptions"/> options.</param>
public FormValueProviderFactory(MvcOptions? options)
{
_options = options;
}

/// <summary>
/// Creates a new <see cref="FormValueProviderFactory"/>.
/// </summary>
public FormValueProviderFactory()
: this(options: null)
{
}

/// <inheritdoc />
public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
{
Expand All @@ -26,13 +45,13 @@ public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
if (request.HasFormContentType)
{
// Allocating a Task only when the body is form data.
return AddValueProviderAsync(context);
return AddValueProviderAsync(context, _options);
}

return Task.CompletedTask;
}

private static async Task AddValueProviderAsync(ValueProviderFactoryContext context)
private static async Task AddValueProviderAsync(ValueProviderFactoryContext context, MvcOptions? options)
{
var request = context.ActionContext.HttpContext.Request;
IFormCollection form;
Expand All @@ -57,7 +76,8 @@ private static async Task AddValueProviderAsync(ValueProviderFactoryContext cont
var valueProvider = new FormValueProvider(
BindingSource.Form,
form,
CultureInfo.CurrentCulture);
CultureInfo.CurrentCulture,
options);

context.ValueProviders.Add(valueProvider);
}
Expand Down
14 changes: 14 additions & 0 deletions src/Mvc/Mvc.Core/src/MvcOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Controllers;
Expand Down Expand Up @@ -379,6 +380,19 @@ public int MaxModelBindingRecursionDepth
/// <value>Defaults to <c>8192</c>.</value>
public int MaxIAsyncEnumerableBufferLimit { get; set; } = 8192;

/// <summary>
/// Gets or sets a value that determines if form values are disallowed to be
/// parsed using <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
/// <remarks>
/// Some form elements (e.g., &lt;input type="text"/&gt;) require culture-specific formatting and parsing because their values are
/// directly entered by the user. However, other inputs (e.g., &lt;input type="number"/&gt;) use culture-invariant
/// formatting both in the HTML source and in the form request. Setting this property to <see langword="true"/>
/// will result in <see cref="CultureInfo.CurrentCulture"/> always being used to parse form values regardless of
/// their original format.
/// </remarks>
public bool SuppressCultureInvariantFormModelBinding { get; set; }

IEnumerator<ICompatibilitySwitch> IEnumerable<ICompatibilitySwitch>.GetEnumerator() => _switches.GetEnumerator();

IEnumerator IEnumerable.GetEnumerator() => _switches.GetEnumerator();
Expand Down
4 changes: 4 additions & 0 deletions src/Mvc/Mvc.Core/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ Microsoft.AspNetCore.Mvc.ApplicationModels.InferParameterBindingInfoConvention.I
*REMOVED*Microsoft.AspNetCore.Mvc.ControllerBase.TryUpdateModelAsync<TModel>(TModel! model, string! prefix, params System.Linq.Expressions.Expression<System.Func<TModel!, object!>!>![]! includeExpressions) -> System.Threading.Tasks.Task<bool>!
Microsoft.AspNetCore.Mvc.ControllerBase.TryUpdateModelAsync<TModel>(TModel! model, string! prefix, Microsoft.AspNetCore.Mvc.ModelBinding.IValueProvider! valueProvider, params System.Linq.Expressions.Expression<System.Func<TModel!, object?>!>![]! includeExpressions) -> System.Threading.Tasks.Task<bool>!
Microsoft.AspNetCore.Mvc.ControllerBase.TryUpdateModelAsync<TModel>(TModel! model, string! prefix, params System.Linq.Expressions.Expression<System.Func<TModel!, object?>!>![]! includeExpressions) -> System.Threading.Tasks.Task<bool>!
Microsoft.AspNetCore.Mvc.ModelBinding.FormValueProvider.FormValueProvider(Microsoft.AspNetCore.Mvc.ModelBinding.BindingSource! bindingSource, Microsoft.AspNetCore.Http.IFormCollection! values, System.Globalization.CultureInfo? culture, Microsoft.AspNetCore.Mvc.MvcOptions? options) -> void
Microsoft.AspNetCore.Mvc.ModelBinding.FormValueProviderFactory.FormValueProviderFactory(Microsoft.AspNetCore.Mvc.MvcOptions? options) -> void
Microsoft.AspNetCore.Mvc.MvcOptions.SuppressCultureInvariantFormModelBinding.get -> bool
Microsoft.AspNetCore.Mvc.MvcOptions.SuppressCultureInvariantFormModelBinding.set -> void
Microsoft.AspNetCore.Mvc.ProblemDetails (forwarded, contained in Microsoft.AspNetCore.Http.Abstractions)
Microsoft.AspNetCore.Mvc.ProblemDetails.Detail.get -> string? (forwarded, contained in Microsoft.AspNetCore.Http.Abstractions)
Microsoft.AspNetCore.Mvc.ProblemDetails.Detail.set -> void (forwarded, contained in Microsoft.AspNetCore.Http.Abstractions)
Expand Down
14 changes: 14 additions & 0 deletions src/Mvc/Mvc.TagHelpers/src/InputTagHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,12 @@ public override void Process(TagHelperContext context, TagHelperOutput output)
break;
}

if (!ViewContext.SuppressCultureInvariantFormElementValueFormatting &&
FormModelBindingHelper.InputTypeUsesCultureInvariantFormatting(inputType))
{
GenerateInvariantCultureMetadata(For.Name, output.PostElement);
}

if (tagBuilder != null)
{
// This TagBuilder contains the one <input/> element of interest.
Expand Down Expand Up @@ -410,6 +416,14 @@ private TagBuilder GenerateTextBox(
htmlAttributes);
}

private static void GenerateInvariantCultureMetadata(string propertyName, TagHelperContent builder)
=> builder
.AppendHtml("<input name=\"")
.Append(FormModelBindingHelper.CultureInvariantFieldName)
.AppendHtml("\" type=\"hidden\" value=\"")
.Append(propertyName)
.AppendHtml("\" />");

// Imitate Generator.GenerateHidden() using Generator.GenerateTextBox(). This adds support for asp-format that
// is not available in Generator.GenerateHidden().
private TagBuilder GenerateHidden(ModelExplorer modelExplorer, IDictionary<string, object> htmlAttributes)
Expand Down
38 changes: 18 additions & 20 deletions src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public class DefaultHtmlGenerator : IHtmlGenerator
private readonly IUrlHelperFactory _urlHelperFactory;
private readonly HtmlEncoder _htmlEncoder;
private readonly ValidationHtmlAttributeProvider _validationAttributeProvider;
private readonly bool _suppressCultureInvariantFormatting;

/// <summary>
/// Initializes a new instance of the <see cref="DefaultHtmlGenerator"/> class.
Expand Down Expand Up @@ -94,6 +95,7 @@ public DefaultHtmlGenerator(
_urlHelperFactory = urlHelperFactory;
_htmlEncoder = htmlEncoder;
_validationAttributeProvider = validationAttributeProvider;
_suppressCultureInvariantFormatting = optionsAccessor.Value.HtmlHelperOptions.SuppressCultureInvariantFormValueFormatting;

// Underscores are fine characters in id's.
IdAttributeDotReplacement = optionsAccessor.Value.HtmlHelperOptions.IdAttributeDotReplacement;
Expand Down Expand Up @@ -134,7 +136,12 @@ public string Encode(object value)
/// <inheritdoc />
public string FormatValue(object value, string format)
{
return ViewDataDictionary.FormatValue(value, format);
return ViewDataDictionary.FormatValue(value, format, CultureInfo.CurrentCulture);
}

private static string FormatValue(object value, string format, IFormatProvider formatProvider)
{
return ViewDataDictionary.FormatValue(value, format, formatProvider);
}

/// <inheritdoc />
Expand Down Expand Up @@ -1282,7 +1289,10 @@ protected virtual TagBuilder GenerateInput(
AddMaxLengthAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);
}

var valueParameter = FormatValue(value, format);
var culture = !_suppressCultureInvariantFormatting && FormModelBindingHelper.InputTypeUsesCultureInvariantFormatting(suppliedTypeString)
? CultureInfo.InvariantCulture
: CultureInfo.CurrentCulture;
var valueParameter = FormatValue(value, format, culture);
var usedModelState = false;
switch (inputType)
{
Expand Down Expand Up @@ -1329,27 +1339,15 @@ protected virtual TagBuilder GenerateInput(

case InputType.Text:
default:
var attributeValue = (string)GetModelStateValue(viewContext, fullName, typeof(string));
if (attributeValue == null)
{
attributeValue = useViewData ? EvalString(viewContext, expression, format) : valueParameter;
}

var addValue = true;
object typeAttributeValue;
if (htmlAttributes != null && htmlAttributes.TryGetValue("type", out typeAttributeValue))
if (string.Equals(suppliedTypeString, "file", StringComparison.OrdinalIgnoreCase) ||
string.Equals(suppliedTypeString, "image", StringComparison.OrdinalIgnoreCase))
{
var typeAttributeString = typeAttributeValue.ToString();
if (string.Equals(typeAttributeString, "file", StringComparison.OrdinalIgnoreCase) ||
string.Equals(typeAttributeString, "image", StringComparison.OrdinalIgnoreCase))
{
// 'value' attribute is not needed for 'file' and 'image' input types.
addValue = false;
}
// 'value' attribute is not needed for 'file' and 'image' input types.
}

if (addValue)
else
{
var attributeValue = (string)GetModelStateValue(viewContext, fullName, typeof(string));
attributeValue ??= useViewData ? EvalString(viewContext, expression, format) : valueParameter;
tagBuilder.MergeAttribute("value", attributeValue, replaceExisting: isExplicitValue);
}

Expand Down
14 changes: 14 additions & 0 deletions src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOptions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace Microsoft.AspNetCore.Mvc.ViewFeatures;
Expand Down Expand Up @@ -60,4 +61,17 @@ public string IdAttributeDotReplacement
/// Gets or sets the way hidden inputs are rendered for checkbox tag helpers and html helpers.
/// </summary>
public CheckBoxHiddenInputRenderMode CheckBoxHiddenInputRenderMode { get; set; } = CheckBoxHiddenInputRenderMode.EndOfForm;

/// <summary>
/// Gets or sets a value that determines if form element values are disallowed to be
/// formatted using <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
/// <remarks>
/// Some form elements (e.g., &lt;input type="text"/&gt;) require culture-specific formatting and parsing because their values are
/// directly entered by the user. However, other inputs (e.g., &lt;input type="number"/&gt;) use culture-invariant
/// formatting both in the HTML source and in the form request. Setting this property to <see langword="true"/>
/// will result in <see cref="CultureInfo.CurrentCulture"/> always being used to format form element values. This may result in
/// invalid HTML being generated.
/// </remarks>
public bool SuppressCultureInvariantFormValueFormatting { get; set; }
}
5 changes: 5 additions & 0 deletions src/Mvc/Mvc.ViewFeatures/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
#nullable enable
*REMOVED*Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<TModel>.Model.get -> TModel?
Microsoft.AspNetCore.Mvc.Rendering.ViewContext.SuppressCultureInvariantFormElementValueFormatting.get -> bool
Microsoft.AspNetCore.Mvc.Rendering.ViewContext.SuppressCultureInvariantFormElementValueFormatting.set -> void
Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelperOptions.SuppressCultureInvariantFormValueFormatting.get -> bool
Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelperOptions.SuppressCultureInvariantFormValueFormatting.set -> void
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<TModel>.Model.get -> TModel
static Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.FormatValue(object? value, string? format, System.IFormatProvider! formatProvider) -> string?
16 changes: 16 additions & 0 deletions src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#nullable enable

using System.Globalization;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
Expand Down Expand Up @@ -93,6 +94,7 @@ public ViewContext(
ValidationSummaryMessageElement = htmlHelperOptions.ValidationSummaryMessageElement;
ValidationMessageElement = htmlHelperOptions.ValidationMessageElement;
CheckBoxHiddenInputRenderMode = htmlHelperOptions.CheckBoxHiddenInputRenderMode;
SuppressCultureInvariantFormElementValueFormatting = htmlHelperOptions.SuppressCultureInvariantFormValueFormatting;
}

/// <summary>
Expand Down Expand Up @@ -136,6 +138,7 @@ public ViewContext(
ValidationSummaryMessageElement = viewContext.ValidationSummaryMessageElement;
ValidationMessageElement = viewContext.ValidationMessageElement;
CheckBoxHiddenInputRenderMode = viewContext.CheckBoxHiddenInputRenderMode;
SuppressCultureInvariantFormElementValueFormatting = viewContext.SuppressCultureInvariantFormElementValueFormatting;

ExecutingFilePath = viewContext.ExecutingFilePath;
View = view;
Expand Down Expand Up @@ -195,6 +198,19 @@ public virtual FormContext FormContext
/// </summary>
public CheckBoxHiddenInputRenderMode CheckBoxHiddenInputRenderMode { get; set; }

/// <summary>
/// Gets or sets a value that determines if form element values are disallowed to be
/// formatted using <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
/// <remarks>
/// Some form elements (e.g., &lt;input type="text"/&gt;) require culture-specific formatting and parsing because their values are
/// directly entered by the user. However, other inputs (e.g., &lt;input type="number"/&gt;) use culture-invariant
/// formatting both in the HTML source and in the form request. Setting this property to <see langword="true"/>
/// will result in <see cref="CultureInfo.CurrentCulture"/> always being used to format form element values. This may result in
/// invalid HTML being generated.
/// </remarks>
public bool SuppressCultureInvariantFormElementValueFormatting { get; set; }

/// <summary>
/// Gets the dynamic view bag.
/// </summary>
Expand Down
Loading