ViewModel小数用法语逗号转换为千位

时间:2018-08-16 20:26:12

标签: c# asp.net asp.net-mvc internationalization

我有以下MVC ViewModel:

public class Payment
{
    [Required]
    [Range(5, 1000)]
    public decimal RebillAmount { get; set; }
}

当我使用以下方式将应用程序语言切换为加拿大法语时:

var cultureInfo = new CultureInfo("fr-CA");

Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;

然后在输入字段中用300,00提交一个小数,在我的控制器中检索该值时,该小数的值会转换为30000吗?

例如:

public ActionResult Save(Payment model)
{
    decimal amount = model.RebillAmount; // <- Returns 30000, not 300.00
}

我在做什么错了?

编辑:

文化是为测试手动设置的(如上所述),但实际上每个用户都可以使用会话变量对其进行配置。

2 个答案:

答案 0 :(得分:3)

您需要编写一个Custom Model Binder来实现。

public class DecimalModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                CultureInfo.CurrentCulture);
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}

在您的Global.asax文件中,将以下内容添加到您的Application_Start方法中

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());

答案 1 :(得分:0)

我在纬度和经度数据上遇到了类似的问题,由于客户端格式而导致逗号消失,我解决了这个问题:

启动配置

        IList<CultureInfo> supportedCultures = new[]
        {
            new CultureInfo("en-US"),
        };

        IList<CultureInfo> supportedCulturesUI = new[]
        {
            new CultureInfo("es-EC"),
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCulturesUI
        });

POCO课程

[Column(TypeName = "decimal(18, 6)")]
[DisplayFormat(DataFormatString = "{0:0.000000}", ApplyFormatInEditMode = true)]
public virtual decimal baLatitude { get; set; }

经度和纬度数据由google maps api捕获并写入视图中的隐藏控件中

<div class="is-hidden">
    <input asp-for="baLatitude">
</div>