微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/aspnet/254473.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐