brika28
brika28

Reputation: 65

DateTime format debugging

So I have been struggling with DateTime formats. I am making an ASP.NET MVC app and I have a DateOfBooking property which is DateTime type. This property books DateTime.Date.Now when the form is sent.

Below is my property and DataAnotations used to format my date. Format which i need is dd/MM/yyyy, but my column in DB (MS SQL Server Managment Studio) is in format yyyy-MM-dd.

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBooking { get; set; }

Anyway, code above enabled me to get a value of my DateOfBooking inside Html.EditorFor helper (inside Edit View which is an MVC templated view) because without it my helper would just show (with date picker) dd/MM/yyyy and now it shows an actual value which is pulled from the DB.

Now because of that line of code above my Index page which is a list of bookings showed date in format yyyy-MM-dd and this is where I got stuck. Luckily after an hour or so i found a solution.

 @foreach (var item in Model) 
    {
    var date = item.DateOfBooking.ToString("dd/MM/yyyy");
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Course.CourseName)
        </td>
        <td> 
            @Html.DisplayFor(modelItem => date)
        </td>

After adding var date everything works just the way I want it. But I dont get it why couldnt I just go like this: @Html.DisplayFor(modelItem => item.DateOfBooking.ToString("dd/MM/yyyy"))

I want to know why couldnt EditorHelper show my date properly without [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] and what difference was made by adding var date?

Upvotes: 0

Views: 396

Answers (1)

Rosco
Rosco

Reputation: 2514

Html.DisplayFor() has a templating system so that you can define how your data should appear throughout your application.

You can create a template in Views/Shared/DisplayTemplates/DateTime.cshtml that will format all DateTime properties when DisplayFor is called. e.g.

 // DateTime.cshtml
 @model System.DateTime
 @Model.ToString("dd/MM/yyyy")

More info https://exceptionnotfound.net/asp-net-mvc-demystified-display-and-editor-templates/

Another way to do it is to just not use DisplayFor and just output the string directly e.g.

@foreach (var item in Model) 
    {
    <tr>
        <td>
            @item.DateOfBooking.ToString("dd/MM/yyyy");
        </td>

This is fine for one or two fields but if all dates are to be formatted consistently it is better to use the template system.

Upvotes: 1

Related Questions