Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 409
Cris Avatar asked Jul 11 '11 20:07

Cris


3 Answers

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

like image 131
Darin Dimitrov Avatar answered Nov 19 '22 17:11

Darin Dimitrov


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; }
}
like image 30
Chase Florell Avatar answered Nov 19 '22 16:11

Chase Florell


Try this. it work for me.

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

like image 34
BJ Patel Avatar answered Nov 19 '22 15:11

BJ Patel