ASP.NET MVC3 - 日期时间格式

发布于 2024-12-10 17:14:20 字数 602 浏览 0 评论 0原文

我正在使用 ASP.NET MVC 3。
我的 ViewModel 看起来像这样:

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

在视图中,我有这样的内容:

<div class="editor-field">
    @Html.EditorFor(model => model.StartDate)
    <br />
    @Html.ValidationMessageFor(model => model.StartDate)
</div>

StartDate 以正确的格式显示,但是当我将其值更改为 19.11.2011 并提交表单时,我收到以下错误消息:“值 '19.11. 2011' 对于开始日期无效。”

任何帮助将不胜感激!

I'm using ASP.NET MVC 3.
My ViewModel looks like this:

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

In view, I have something like this:

<div class="editor-field">
    @Html.EditorFor(model => model.StartDate)
    <br />
    @Html.ValidationMessageFor(model => model.StartDate)
</div>

StartDate is displayed in correct format, but when I change it's value to 19.11.2011 and submit the form, I get the following error message: "The value '19.11.2011' is not valid for StartDate."

Any help would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

娇纵 2024-12-17 17:14:20

您需要在 web.config 文件的全球化元素中设置正确的区域性,其中 dd.MM.yyyy 是有效的日期时间格式:

<globalization culture="...." uiCulture="...." />

例如,这是德语的默认格式:de -DE


更新:

根据您在评论部分的要求,您希望保留应用程序的美国文化,但仍使用不同的日期格式。这可以通过编写自定义模型绑定器来实现:

using System.Web.Mvc;
public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName, 
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

您将在 Application_Start 中注册该模型绑定器:

ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());

You need to set the proper culture in the globalization element of your web.config file for which dd.MM.yyyy is a valid datetime format:

<globalization culture="...." uiCulture="...." />

For example that's the default format in german: de-DE.


UPDATE:

According to your requirement in the comments section you want to keep en-US culture of the application but still use a different formats for the dates. This could be achieved by writing a custom model binder:

using System.Web.Mvc;
public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName, 
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

which you will register in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());
雅心素梦 2024-12-17 17:14:20

根据您的评论,我看到您想要的只是当前的英语,但日期格式不同(如果我错了,请纠正我)。

事实上,DefaultModelBinder 使用服务器的区域性设置来处理表单数据。所以我可以说服务器使用“en-US”文化,但日期格式不同。

您可以在 Application_BeginRequest 中执行类似的操作,然后就完成了!

protected void Application_BeginRequest()
{
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = info;
}

Web.Config

<globalization culture="en-US" />

Based upon your comment I see all you want is an english current but with a different date format (Correct me if I'm wrong).

The fact is the DefaultModelBinder uses the culture settings of the server for form data. So I can say the server use "en-US" culture but with a different date format.

You can do something like this in the Application_BeginRequest and you are done!

protected void Application_BeginRequest()
{
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = info;
}

Web.Config

<globalization culture="en-US" />
柠栀 2024-12-17 17:14:20

将以下代码添加到 global.asax.cs 文件

protected void Application_BeginRequest()  
{        
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());     
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = info;     
}

并将以下代码添加到 下的 web.config

<globalization culture="en-US">;

Added this below code to global.asax.cs file

protected void Application_BeginRequest()  
{        
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());     
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = info;     
}

And added the below to web.config under <system.web>

<globalization culture="en-US">;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文