asp.net-mvcasp.net-mvc-4data-annotations

Why is DisplayFormat DataFormatString not working?


I have a property in my view model as follows:

[Editable(false)]
[Display(Name = "Date")]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime MovementDate { get; set; }

Yet the markup

<td>
    @Html.DisplayFor(modelItem => item.MovementDate)
</td>

renders the date value as 2013/05/15 12:00:00 AM.

What am I doing wrong? My model:

public class WithDateModel
{
    [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}")]
    public DateTime TheDate { get; set; }
    public WithDateModel()
    {
        TheDate = DateTime.Now;
    }
}

My view:

@model ParkPay.WebTests.Models.WithDateModel
@Html.DisplayFor(m => m.TheDate)
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

What gets rendered:

2013/05/25 02:23:37 AM

Solution

  • Why are you using ApplyFormatInEditMode if you have set [Editable(false)]? All ApplyFormatInEditMode does is format the date if you have it in a text box or something for editing, which you probably won't because of the aforementioned.

    I was able to get the date to display correctly using the following:

    [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}")]
    public DateTime Date 
    {
        get
        {
            return DateTime.Now;
        }
        set
        {
            Date = DateTime.Now;
        }
    }
    

    and in the view (with resulting output):

    @Html.DisplayFor(x => x.Date)        // 2013/05/23
    <br />
    @Model.Date                          // 23/05/2013 09:57:56
    <br />
    @Html.DisplayFor(x => Model.Date)    // 2013/05/23
    

    Hope this helps.