I have this attribute in my view model:
[DataType(DataType.DateTime)] public DateTime? StartDate { get; set; }
If I want to display the date, or populate a textbox with the date, I have these:
<%: Model.StartDate %> <%: Html.TextBoxFor(m => m.StartDate) %>
Whenever the date is displayed, it's displayed like: 01/01/2011 12:00:00 AM
But I'd like to only display 01/01/2011
Is there a way to apply a display format with data annotations? I don't want to have to go to every instance where I display a date, and add some code to format it.
To create the View , right click on view folder and then click Add view. Now specify the view name as Index or as you wish, choose create scaffolding template and model class EmpModel. cs and click on Add button.
For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
Try tagging it with:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
Did you try this?
[DataType(DataType.Date)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With