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" .

It actually displays as: @Html.LabelFor(model => model.DtNews) , and I don't know where and how I can put the Format () function.

Data is extracted from db using EF.

How can i do this?

Thanks!

+6
source share
6 answers
 @Html.LabelFor(model => model.DtNews) @Html.EditorFor(model => model.DtNews) 

and in your view model you can use the [DisplayFormat] attribute

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

Now you will tell me that this class is generated by the EF framework, to which I would answer you: YOU SHOULD NOT USE YOUR AUTOMATED EF MODELS IN YOUR KINDS . You must define and use viewing models. View models are classes that are specifically tailored to the requirements of your views. For example, in this particular view, you have a requirement to format dates in a certain way: ideal for view models:

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

then your controller action can request your repository and get the domain model (auto-generated EF object) and map it to the view model. He will then pass this view model into the view.

+6
source

I would just drop the buddy class on model.DtNews

The 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; } } 
+1
source

Try it. it works for me.

@ Model.DtNews.Value.ToString ("dd-MM-yyyy")

+1
source

If DtNews is a DateTime , try the following:

 @Html.LabelFor(model => model.DtNews.ToString("dd/MM/yyyy")); 
0
source

@Html.LabelFor(model => model.DtNews.ToString("dd/MM/yyyy"))

^ should do the trick.

You can also use editor / display templates as discussed here .

0
source

Use it

@ Html.TextBoxFor (m => m.MktEnquiryDetail.CallbackDate, "{0: dd / MM / yyyy}")

0
source

Source: https://habr.com/ru/post/892530/


All Articles