在ASP.NET MVC应用程序更改日期格式 [英] Change date format in ASP.NET MVC application

查看:320
本文介绍了在ASP.NET MVC应用程序更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更改日期格式为 DD.MM.YYYY 。我收到客户端验证错误,因为ASP.NET MVC的日期格式是我所期望的服务器上的不同。

I need to change date format to be dd.MM.yyyy. I am getting client side validation error because ASP.NET MVC date format is different from what I expect on the server.

为了改变ASP.NET MVC的日期格式我尝试:

In order to change ASP.NET MVC date format I tried:

Web.config文件:

Web.config:

<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中:

Even 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调用的第二个参数没有做什么,你认为它。

The second argument you were passing to the EditorFor call doesn't do what you think it does.

有关此自定义编辑模板,因为你指定的格式明确对您的视图模型属性的&LT;全球化&gt;在你的web.config 元素和当前线程文化将有0的效果。当前线程文化是用来与标准模板,当你没有覆盖与 [DisplayFormat] 属性的格式。

For this custom editor template, since you specified the format explicitly on your view model property the <globalization> element in your web.config and the current thread culture will have 0 effect. The current thread culture is used with the standard templates and when you didn't override the format with the [DisplayFormat] attribute.

这篇关于在ASP.NET MVC应用程序更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆