Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC DisplayFormat

In my model I have the following DataAnnotations on one of my properties

[Required(ErrorMessage = "*")] [DisplayFormat(DataFormatString = "{0:d}")] [DataType(DataType.Date)] public DateTime Birthdate { get; set; } 

The required annotation works great, I added the other 2 to try and remove the time. It gets bound to an input in the view using

<%=Html.TextBoxFor(m => m.Birthdate, new { @class = "middle-input" })%> 

However whenever the view loads I still get the time appearing in the input box. Is there anyway to remove this using DataAnnotations?

like image 762
Gavin Avatar asked Jan 04 '10 19:01

Gavin


2 Answers

The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor.

like image 175
Brad Wilson Avatar answered Oct 11 '22 10:10

Brad Wilson


As Brad said it dosn't work for TextBoxFor but you'll also need to remember to add the ApplyFormatInEditMode if you want it to work for EditorFor.

[DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd/MM/yy}", ApplyFormatInEditMode=true )] public System.DateTime DateCreated { get; set; } 

Then use

@Html.EditorFor(model => model.DateCreated) 
like image 40
Paul Johnson Avatar answered Oct 11 '22 08:10

Paul Johnson