【问题标题】:Apply model metadata on complex objects将模型元数据应用于复杂对象
【发布时间】:2012-07-10 20:22:41
【问题描述】:

我有以下场景

public class Foo {
    public Bar FooBar { get; set; }
}

public class Bar {
    [DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
    public DateTime BirthDay { get; set; }
}

现在当我使用 EditorFor 时,我想在 DateTime 上应用 DataFormatString

@Html.EditorFor(x => x.FooBar.BirthDay);

上面的代码没有使用 DisplayFormatAttribute 正确渲染日期,我该如何解决呢?

【问题讨论】:

    标签: asp.net-mvc-3 modelmetadata


    【解决方案1】:

    我想你可能不得不使用这个。

    public class Bar {
        [DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd/MM/yy}", ApplyFormatInEditMode=true )]
        public DateTime BirthDay { get; set; }
    }
    

    或者你可以这样使用

    [DisplayFormat(DataFormatString = "{0:d}")]
    [DataType(DataType.Date)]
    public DateTime BirthDay { get; set; }
    

    在你看来,你可以试试这个。

    @Html.EditorFor(x => x.FoorBar.BirthDay.ToString("dd/MM/yyyy"))
    

    【讨论】:

    • 这是结果 7/11/2012 12:00:00 AM
    • 你为什么不尝试 html.TextBoxFor 而不是 html.EditodFor ...我相信这适用于 TextBoxFor
    • 不,与那个不一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多