asp.net-mvc-3 – ASP.NET MVC3 – DateTime格式

我使用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’对StartDate无效。

任何帮助将不胜感激!

解决方法

您需要在web.config文件的全球化元素中设置正确的文化,其中dd.MM.yyyy是有效的datetime格式:
<globalization culture="...." uiCulture="...." />

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

更新:

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

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....