Asp.net-Mvc

在 ASP.NET MVC 應用程序中更改日期格式

  • May 16, 2017

我需要將日期格式更改為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 呼叫的第二個參數並沒有按照您的想法執行。

對於此自定義編輯器模板,由於您在視圖模型屬性上明確指定了格式,因此<globalization>web.config 中的元素和目前執行緒文化將具有 0 效果。目前執行緒區域性與標準模板一起使用,並且當您沒有使用[DisplayFormat]屬性覆蓋格式時。

引用自:https://stackoverflow.com/questions/17106105