在Razor中将日期转换为ToShortDateString

Rai*_*ika 14 razor

我有一个必须在编辑视图中显示的DateTime字段

@Html.EditorFor( model => model.StartDate )
Run Code Online (Sandbox Code Playgroud)

我怎么能用这样的东西;

@Html.EditorFor( model => model.StartDate.ToShortDateString() )
Run Code Online (Sandbox Code Playgroud)

或任何用于更改视图的DateTime的自定义函数.

Dar*_*rov 20

[DisplayFormat]在视图模型上使用该属性:

public class MyViewModel
{
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }

    ...

}
Run Code Online (Sandbox Code Playgroud)

然后在你的视图中简单地说:

@model MyViewModel
...
@Html.EditorFor(model => model.StartDate)
Run Code Online (Sandbox Code Playgroud)