加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 19:10:23 所属栏目:asp.Net 来源:网络整理
导读:我使用ASP.NET MVC 3。 我的ViewModel看起来像这样: public class Foo{ [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}",ApplyFormatInEditMode = true)] public DateTime StartDate { get; set; } ...} 在我看来,我有这样
我使用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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读