gpt4 book ai didi

asp.net-mvc - 在 ASP.NET MVC 应用程序中更改日期格式

转载 作者:行者123 更新时间:2023-12-03 22:08:40 43 4
gpt4 key购买 nike

我需要将日期格式更改为 dd.MM.yyyy .我收到客户端验证错误,因为 ASP.NET MVC 日期格式与我在服务器上期望的格式不同。

为了更改 ASP.NET MVC 日期格式,我尝试了:

网页配置:

<globalization uiCulture="ru-RU" culture="ru-RU" />

模型:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime? ServiceCreatedFrom { get; set; }

编辑器模板:
@model DateTime?
@Html.TextBox(string.Empty, (Model.HasValue
? Model.Value.ToString("dd.MM.yyyy")
: string.Empty), new { @class = "date" })

看法:
@Html.EditorFor(m => m.ServiceCreatedFrom, new { @class = "date" })

甚至 Global.asax:
public MvcApplication()
{
BeginRequest += (sender, args) =>
{
var culture = new System.Globalization.CultureInfo("ru");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
};
}

没有什么对我有用。

最佳答案

以下应该工作:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime? ServiceCreatedFrom { get; set; }

并在您的编辑器模板中:
@model DateTime?
@Html.TextBox(
string.Empty,
ViewData.TemplateInfo.FormattedModelValue,
new { @class = "date" }
)

进而:
@Html.EditorFor(x => x.ServiceCreatedFrom)

您传递给 EditorFor 调用的第二个参数与您认为的不同。

对于这个自定义编辑器模板,由于您在 View 模型属性中明确指定了格式 <globalization> web.config 中的元素和当前线程文化将具有 0 效果。当前线程区域性与标准模板一起使用,并且当您没有使用 [DisplayFormat] 覆盖格式时属性。

关于asp.net-mvc - 在 ASP.NET MVC 应用程序中更改日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17106105/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com