创建ViewModel时,从多个模型“继承”DataAnnotations

时间:2013-11-04 15:49:48

标签: c# asp.net-mvc data-annotations

我的模型类 Base1 上有一个System.ComponentModel.DataAnnotations格式化DateTime类型。

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
 public DateTime Date { get; set; }

当我从 Base1 Base2 模型

创建另一个模型时
public class Combined
    {       
        public Base1 Name1 { get; set; }
        public Base2 Name2 { get; set; }
    }

Name1实例中的DateTime格式更改为默认值(数据和时间)。

有没有办法从基础模型“继承”DataAnnotations,所以我不必在View层上格式化显示数据?

1 个答案:

答案 0 :(得分:1)

我知道这不是你所要求的直接答案,但我强烈建议使用显示/编辑模板。这种类型的东西正是它们的设计目标。例如,您可以创建一个处理DateTime的模板(将其放在Views\Shared\EditorTemplates\DateTime.cshtml中)。然后在模板中:

@model System.DateTime
@Html.TextBox(string.Empty, Model.ToString("yyyy-MM-dd"))

然后当然使用它:

@Html.EditorFor(...)

如果您有多个模板,可以为它们命名并选择使用哪个模板。显示模板也是如此。

相关问题