【发布时间】:2011-07-11 20:33:04
【问题描述】:
我有一个视图,需要在其上显示格式为 "dd/MM/yyyy" 的日期。
实际上它显示为:@Html.LabelFor(model => model.DtNews),我不知道在哪里以及如何放置 Format() 函数。
使用 EF 从数据库中检索数据。我该怎么做?
【问题讨论】:
标签: asp.net-mvc razor date-format
我有一个视图,需要在其上显示格式为 "dd/MM/yyyy" 的日期。
实际上它显示为:@Html.LabelFor(model => model.DtNews),我不知道在哪里以及如何放置 Format() 函数。
使用 EF 从数据库中检索数据。我该怎么做?
【问题讨论】:
标签: asp.net-mvc razor date-format
@Html.LabelFor(model => model.DtNews)
@Html.EditorFor(model => model.DtNews)
在您的视图模型上,您可以使用[DisplayFormat] 属性
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DtNews { get; set; }
现在你要告诉我这个类是由 EF 框架生成的,我会回复你:你不应该在你的视图中使用你的 EF 自动生成模型。您应该定义和使用视图模型。视图模型是专门为您的视图要求定制的类。例如,在此特定视图中,您需要以特定方式格式化日期:非常适合视图模型:
public class MyViewModel
{
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DtNews { get; set; }
}
然后您的控制器操作可以查询您的存储库并获取域模型(EF 自动生成的实体)并将其映射到视图模型。然后它将这个视图模型传递给视图。
【讨论】:
我只想在你的model.DtNews 上开设一个好友课程
好友班将装饰您现有的模型
[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; }
}
【讨论】:
试试这个。它对我有用。
@Model.DtNews.Value.ToString("dd-MM-yyyy")
【讨论】:
【讨论】:
如果DtNews 是DateTime,那么试试这个:
@Html.LabelFor(model => model.DtNews.ToString("dd/MM/yyyy"));
【讨论】:
使用这个
@Html.TextBoxFor(m => m.MktEnquiryDetail.CallbackDate, "{0:dd/MM/yyyy}")
【讨论】: