Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model property formatting

Tags:

c#

asp.net-mvc

I have a model with a DateTime propery:

[DisplayName("Updated")]
public DateTime lastUpdatedDate { get; set; }

At the moment, I think I am incorrectly handling the formatting of the datetime in the view.

<tr>
    <td>@Html.LabelFor(m=>m.lastUpdatedDate)</td>
    <td>@Html.Label(Model.lastUpdatedDate.ToLongDateString())</td>
</tr>

I am sure this is wrong. Firstly, should I do the formatting in the model, and return string (In the model used for displaying the date - the Update model needs the DateTime type for the control)? But it gets complicated - timezones. Should I manipulate the value of the date time (based on a timezone selection by the user on registration) in the model on the get; .. thing? (What's the called? The getter?? hehe).

Just trying to make my code friendly to work with, while I learn MVC.

like image 543
Craig Avatar asked Jul 14 '26 19:07

Craig


1 Answers

If you want to elegantly deal with timezones, I suggest you read this answer. For simple formatting the DateTime property in your model, decorate it with the [DisplayFormat] attribute:

[DisplayName("Updated")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime lastUpdatedDate { get; set; }

and in your view:

@Html.DisplayFor(x => x.lastUpdatedDate)
like image 50
chridam Avatar answered Jul 17 '26 16:07

chridam