MVC 3 Validation - Format datetime

1.8k Views Asked by At

I want to format my DateTime field in razor in a clean way.

[MetadataType(typeof(Guestbook_Validation))]
public partial class web_GuestBook
{
    // Partial generated EF
}

[Bind(Exclude="Id")]
public class Guestbook_Validation
{
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? DateEntered { get; set; }
}

Then

@item.DateEntered

But its still displaying as 05/01/2009 13:28:14

Where am I going wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

Use Html.DisplayFor(x => x.DateEntered) if you want the display format to be used.

1
On

See this answer:

Set DataFormatString for MVC3 DateTime

You have to use EditorFor in the view and use ApplyFormatInEditMode = true in your viewmodel - For textbox. To display only, use DisplayFor