1

I have a model with a property which is a generic looking something like:

class PairedData<T>
{
    public T Value {get;set;}
    public bool IsValid {get;set;}
}

In the model I have:

class SomeModel
{
    [UIHint ("PairedInt")]
    public PairedData<int> SomeInt {get;set;}

    [UIHint ("PairedDateTime")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}"]
    public PairedData<DateTime> SomeDate {get;set;}
}

Then in my Display Template for PairedDateTime I have:

 @model PairedData<DateTime>

 @Html.DisplayFor(m => m.Value)

The problem is that the DisplayFor doesn't apply the date format. The reason is obvious enough - the DisplayFormat attribute is on SomeDate, not on the Value property, so is not being read.

So the question is, is there a way to tell the DisplayFor to read the attribute from somewhere else? Or is there a way to manually pass the same information to DisplayFor within the Display Template? Or is there a way to apply the attribute to Value only in the DateTime instantiation (unlikely, I think)?

Thanks in advance.

Jasper Kent
  • 3,546
  • 15
  • 21

2 Answers2

1

You can try to format this on view if you are sure this will always be a DateTime:

@Html.DisplayFor(m => m.Value, "{0:dd/MM/yyyy}", new {maxlength=10})

This works, but I would recommend you the approach suggested by Daryl and bkaid here: https://stackoverflow.com/a/6733855/1638261

Community
  • 1
  • 1
jomsk1e
  • 3,585
  • 7
  • 34
  • 59
  • Thanks - that'll do in this specific situation. I'd still be interested in a more general approach. – Jasper Kent Apr 07 '16 at 09:37
  • Actually, that doesn't seem to work. The string parameter is a template name, not a date format. I don't see anything in the linked article about formatting. – Jasper Kent Apr 07 '16 at 09:45
0

The DataType Annotation will give you the date format by default mm/dd/yyyy and the input for this will be a drop down list and combined with the DisplayFormat should give you the results that you are looking for.

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
Patrick Mcvay
  • 2,221
  • 1
  • 11
  • 22
  • The problem is I'm using a generic so although that annotation is appropriate for the DateTime instantiation, it's not for, say, int. The question remains - how do I apply different attribute to different instantiations of the generic? – Jasper Kent Apr 10 '16 at 19:01