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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - that'll do in this specific situation. I'd still be interested in a more general approach.
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.
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)]

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.