I have a View on which I need to display a date formatted in "dd/MM/yyyy"
.
Actually it is displayed as: @Html.LabelFor(model => model.DtNews)
and I don't know where and how I can put the Format() function.
Data is retrieved from the database using EF. How can I do it?
@Html.LabelFor(model => model.DtNews)
@Html.EditorFor(model => model.DtNews)
and on your view model you could use the [DisplayFormat]
attribute
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DtNews { get; set; }
Now you're gonna tell me that this class is generated by the EF framework to which I would respond to you: YOU SHOULD NOT USE YOUR EF AUTOGENERATED MODELS IN YOUR VIEWS. You should define and use view models. The view models are classes specifically tailored to the requirements of your views. For example in this particular view you have a requirement to format the dates in a particular way: perfect fit for view models:
public class MyViewModel
{
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DtNews { get; set; }
}
then your controller action could query your repository and fetch the domain model (EF autogenerated entity) and map it to a view model. Then it will pass this view model to the view.
I'd just throw a buddy class on your model.DtNews
A buddy class will decorate your existing model
[MetadataType(NewsMetadata)]
public partial class News // this is the same name as the News model from EF
{ /* ... */ }
/* Metadata type */
public class NewsMetadata
{
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DtNews { get; set; }
}
Try this. it work for me.
@Model.DtNews.Value.ToString("dd-MM-yyyy")
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