c#-数字格式在ASP.NET Core中不起作用
作者:互联网
我尝试在我的应用程序(Azure中的.Net 4.5.2 Full Framework上运行的ASP.NET Core)中允许使用小数.该应用程序被配置为仅在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:#.###},它也不能正常工作,并且将类型更改为十进制?
[Display(Name = "ContainerWeight", ResourceType = typeof(SharedResource))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N3}")]
public float? Weight { get; set; }
如果我提交表单,则使用例如我的机器是英文Windows计算机上的111,222,如果我使用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格式正常工作时遇到了类似的麻烦,但是弄清楚了,这对我来说似乎很难.
解决方法:
根据文档,您必须使用本地化中间件来设置当前的请求区域性.您必须在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和控制器级别进行了验证.
标签:dataformat,asp-net-core,asp-net,c,localization 来源: https://codeday.me/bug/20191026/1939106.html