ASP.NET核心本地化十进制字段点和逗号

Max*_*Max 4 c# asp.net asp.net-mvc asp.net-core

我有一个本地化的ASP.NET核心Web应用程序:en-US和it-IT.

在en-US上,小数点分隔符是点,在它中 - 小数点分隔符是逗号.

我有这个ViewModel

public class MyViewModel 
{
    public int Id {get; set; }

    // Omitted

    public decimal? Amount{get; set;}

}
Run Code Online (Sandbox Code Playgroud)

对于在en-US上渲染创建/编辑页面时的十进制字段,html文本框呈现

1000.00

如果我POST表单,操作完成没有错误.

到现在为止还挺好.

当我在上渲染创建/编辑页面时,IT渲染html文本框

1000,00(注意逗号)

如果我尝试发布形式(客户端)验证失败

字段金额必须是数字.

我读到了关于IModelBinder但我理解的是当表单在服务器上发布时映射viewModel,在我的情况下我被客户端验证阻止了.

更好的是在en-US时使用dot,而在IT时使用逗号,但只使用点就可以了

Max*_*Max 6

在挖掘深度问题后,我找到了两个解决方案:

Stephen Muecke的评论解释了如何将输入所需的jquery添加到逗号和点验证中

自定义InputTagHelper,将逗号转换为点.这里我只添加了一个十进制类型,但显然你可以添加float和double.

[HtmlTargetElement("input", Attributes = ForAttributeName, TagStructure = TagStructure.WithoutEndTag)]
public class InvariantDecimalTagHelper : InputTagHelper
{
    private const string ForAttributeName = "asp-for";

    private IHtmlGenerator _generator;

    [HtmlAttributeName("asp-is-invariant")]
    public bool IsInvariant { set; get; }

    public InvariantDecimalTagHelper(IHtmlGenerator generator) : base(generator)
    {
        _generator = generator;
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);

        if (IsInvariant && output.TagName == "input" && For.Model != null && For.Model.GetType() == typeof(decimal))
        {
            decimal value = (decimal)(For.Model);
            var invariantValue = value.ToString(System.Globalization.CultureInfo.InvariantCulture);
            output.Attributes.SetAttribute(new TagHelperAttribute("value", invariantValue));                
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用这个第二个解决方案,您只需在输入中添加asp-is-invariant,就像这样

 <input asp-for="AmountSw" class="form-control" asp-is-invariant="true" />
Run Code Online (Sandbox Code Playgroud)