Search code examples
asp.net-mvcrazordate-format

How to format date in lambda expression in Razor View?


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?


Solution

  • @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.