数字格式在ASP.NET Core中不起作用

时间:2016-08-14 18:04:08

标签: c# asp.net localization asp.net-core dataformat

我尝试在我的应用程序中允许小数(ASP.NET中运行.Net 4.5.2 Full Framework的ASP.NET核心)。该应用程序配置为仅在Startup.cs中使用自定义DateTime格式的de-DE文化:

var dtf = new DateTimeFormatInfo
{
    ShortDatePattern = "dd.MM.yyyy",
    LongDatePattern = "dd.MM.yyyy HH:mm",
    ShortTimePattern = "HH:mm",
    LongTimePattern = "HH:mm"
};

services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new List<CultureInfo>
    {
        //new CultureInfo("en-US") { DateTimeFormat = dtf },
        //new CultureInfo("en") { DateTimeFormat = dtf },
        new CultureInfo("de-DE") { DateTimeFormat = dtf },
        new CultureInfo("de") { DateTimeFormat = dtf }
        //new CultureInfo("en-US"),
        //new CultureInfo("en"),
        //new CultureInfo("de-DE"),
        //new CultureInfo("de")
    };

    options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

我的模型看起来像这样,我也尝试使用{0:#.###},这也无法将类型更改为decimal?

[Display(Name = "ContainerWeight", ResourceType = typeof(SharedResource))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N3}")]
public float? Weight { get; set; }

如果我提交表单,如果我使用例如,我会收到JavaScript验证错误我的机器上是111,222,这是一台美国Windows机器,如果我使用111.222,我的控制器会出现模型错误。在德国机器上,它看起来完全相反(我要求有人为我检查)。这是视图的一部分:

<div class="form-group col-sm-12 col-md-6">
    <label asp-for="Weight" class="col-md-3 control-label"></label>
    <div class="col-md-9">
        <input asp-for="Weight" class="form-control" />
        <span asp-validation-for="Weight" class="text-danger" />
    </div>
</div>

我在使用DateTime格式时遇到了类似的问题,但是想出来了,这个对我来说似乎很难。

1 个答案:

答案 0 :(得分:4)

根据文档,您必须使用本地化中间件来设置当前的请求文化。您必须使用Configure方法,而不是ConfigureService方法。

我在Configure方法中做了以下事情。

var dtf = new DateTimeFormatInfo
{
    ShortDatePattern = "dd.MM.yyyy",
    LongDatePattern = "dd.MM.yyyy HH:mm",
    ShortTimePattern = "HH:mm",
    LongTimePattern = "HH:mm"
};

var supportedCultures = new List<CultureInfo>
{
    //new CultureInfo("en-US") { DateTimeFormat = dtf },
    //new CultureInfo("en") { DateTimeFormat = dtf },
    new CultureInfo("de-DE") { DateTimeFormat = dtf },
    new CultureInfo("de") { DateTimeFormat = dtf }
    //new CultureInfo("en-US"),
    //new CultureInfo("en"),
    //new CultureInfo("de-DE"),
    //new CultureInfo("de")
};

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

之后我创建了样本模型。

public class TestModel
{
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N3}")]
    public float? Weight { get; set; }
}

从UI传递值111,112,它也在UI和控制器级别成功验证。