ASP.NET MVC3 - 日期时间格式 [英] ASP.NET MVC3 - DateTime format

查看:24
本文介绍了ASP.NET MVC3 - 日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

公共类Foo{[数据类型(数据类型.日期)][DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]公共日期时间开始日期 { 获取;放;}...}

看来,我有这样的事情:

@Html.EditorFor(model => model.StartDate)<br/>@Html.ValidationMessageFor(model =>model.StartDate)

StartDate 以正确的格式显示,但是当我将它的值更改为 19.11.2011 并提交表单时,我收到以下错误消息:值 '19.11.2011' 对 StartDate 无效."

任何帮助将不胜感激!

解决方案

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

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

<小时>

更新:

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

使用 System.Web.Mvc;公共类 MyDateTimeModelBinder : DefaultModelBinder{公共覆盖对象 BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext){var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);if (!string.IsNullOrEmpty(displayFormat) && value != null){日期时间日期;displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);//使用DisplayFormat属性中指定的格式来解析日期if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)){归期;}别的{bindingContext.ModelState.AddModelError(bindingContext.ModelName,string.Format("{0} 是无效的日期格式", value.AttemptedValue));}}返回 base.BindModel(controllerContext, bindingContext);}}

您将在 Application_Start 中注册:

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

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!

解决方案

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());

这篇关于ASP.NET MVC3 - 日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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