1
votes

I'm working on a project that is meant to display a list of messages and the times/dates the messages are sent. The C# for setting the date is:

 public class Message
{
   public DateTime MessageSent { get; set; }
}

However this grabs both the date and time, but say if I wanted to display just the date I find myself doing this in the Razor:

<span>@Html.DisplayFor(modelItem => item.MessageSent.Day)/@Html.DisplayFor(modelItem => item.MessageSent.Month)/@Html.DisplayFor(modelItem => item.MessageSent.Year)</span>

But this seems really illogical. Is there a way I can chain day/month/year into just one statement? I know I can separate the date and time in the C# but is it possible do it just in Razor?

1
Just add a [DisplayFormat(DataFormatString = "{0:d}")] attribute on your property and it will render the correct formatuser3559349

1 Answers

1
votes

Try the below syntax

@Html.DisplayFor(modelItem => item.MessageSent.ToString("dd/MM/yyyy"))