Reputation: 3676
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.
Upvotes: 1
Views: 785
Reputation: 2281
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)]
Upvotes: 0
Reputation: 3625
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
Upvotes: 1