0

Is there some way to use the DataType annotation on a list (IEnumerable) of objects, so that when I use DisplayFor in my template it will format the date correctly?

model:

public class CallOverview
{

    [DataType(DataType.Date), DisplayFormat(DataFormatString = @"{0:dddd dd MMMM yyyy}")]
    public IEnumerable<DateTime> Days { get; set; }

}

view:

@foreach (var day in Model.Days)
{

    <p>@Html.DisplayFor(modelItem => day)</p>

}

output:

31/07/2012 00:00:00
0

3 Answers 3

1

I think the reason you are seeing this behavior is because you are applying the DataType attribute to the enumeration, not to its individual values. Something like this should work though:

model:

public class CallOverview
{
    public IEnumerable<DateTimeWrapper> Days { get; set; }

    public class DateTimeWrapper
    {
        [DataType(DataType.Date), DisplayFormat(DataFormatString = @"{0:dddd dd MMMM yyyy}")]
        public DateTime Value { get; set; }
    }
}

view:

@foreach (var day in Model.Days)
{
    <p>@Html.DisplayFor(m => day.Value)</p>    
}
Sign up to request clarification or add additional context in comments.

1 Comment

That would work, but its a little verbose. Would be nice to be able to do something like [DataTypeEnumerable(DataType.Date)]
0

You can do what you are trying to do. You need to introduce a new Type to persist the collection via EF.

See this answer for details: https://stackoverflow.com/a/43773647/1742393

public class CallOverview
{

    [DataType(DataType.Date), DisplayFormat(DataFormatString = @"{0:dddd dd MMMM yyyy}")]
    public PersistableDateTimeCollection<DateTime> Days { get; set; }

}

Comments

-2

The answer is it can't be done.

Comments

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.