Chris Hermut
Chris Hermut

Reputation: 1758

"Inheriting" DataAnnotations from multiple models when creating a ViewModel

I have a System.ComponentModel.DataAnnotations on my model class Base1 that formats DateTime type.

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

When I create another model from Base1 and Base2 models

public class Combined
    {       
        public Base1 Name1 { get; set; }
        public Base2 Name2 { get; set; }
    }

DateTime format in Name1 instance changes to default (data and time).

Is there a way to "inherit" DataAnnotations from base models so I don't have to format display data on View layer?

Upvotes: 2

Views: 141

Answers (1)

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15138

I know it's not a direct answer to what you're asking, but I would highly recommend using display/editor templates. This type of thing is exactly what they have been designed for. For example you can create a template that handles DateTime (place it in Views\Shared\EditorTemplates\DateTime.cshtml). Then in the template:

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

Then of course use it like:

@Html.EditorFor(...)

If you have multiple templates you can name them and chose which one to use. Same goes for display templates.

Upvotes: 1

Related Questions