在日期时间只在剃刀中获得MM / dd / yyyy

我有这样的代码

@Html.EditorFor(model => model.VoluntaryWork.DateEnded) @Html.ValidationMessageFor(model => model.VoluntaryWork.DateEnded) 

并且工作正常。 但它正从我的sql中检索整个数据

当前代码的输出

3/22/2017 12:00:00 AM

期望的输出

3/22/2017

我尝试使用像这样的代码@Html.ValidationMessageFor(model => model.VoluntaryWork.DateEnded.Value.ToShortDateString())但是它给了我一个错误

模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式

我尝试在谷歌搜索并发现这个但对我来说这是一个很长的方法? 我是那种方法的新手,所以我不知道如何使用它。

有没有最短的方法来实现所需的输出?

更新

控制器代码

 PersonVoluntaryWork pvw = db.PersonVoluntaryWorks.Single(vw => vw.VoluntaryWorksId == id); return PartialView("_NewPersonVoluntaryWorks", pvw); 

视图

 @model System.Models.PersonVoluntaryWork @using (Html.BeginForm()) {  @Html.EditorFor(model => model.VoluntaryWork.DateEnded) @Html.ValidationMessageFor(model => model.VoluntaryWork.DateEnded)  } 

您可以将DisplayFormatAttribute应用于您的属性

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

并且EditorFor()方法将EditorFor()该格式。

或者你可以使用

 @Html.TextBoxFor(m => m.VoluntaryWork.DateEnded, "{0:d}", null) 

最简单的方法是:

 @Html.TextBoxFor(model => model.VoluntaryWork.DateEnded, "{0:dd/MM/yyyy}") 

Fortunatly EditorFor hepler没有这种超载。 这就是你应该使用TextBoxFor html helper的原因

更新:

MVC 3没有这种过载。 因此,解决问题的最简单方法是使用非强类型帮助器,如下所示:

 @Html.TextBox("VoluntaryWork_DateEnded", Model.VoluntaryWork.DateEnded.HasValue ? Model.VoluntaryWork.DateEnded.Value.ToString("dd/MM/yyyy") : DateTime.Now.ToString("dd/MM/yyyy")) 

在模型中注释您的属性,如下所示:

[数据类型(DataType.Date)]
公共日期时间? DateEnded {get; 组; }

它将隐藏dateEnded属性的时间。

试试这个代码

 @Html.EditorFor(model => model.VoluntaryWork.DateEnded, new { @Value = model.VoluntaryWork.DateEnded.ToString("MM/dd/yyyy") }) 

要向模型添加属性,请添加以下代码:

 public string ReturnDateForDisplay { get { return this.VoluntaryWork.DateEnded.ToString("d"); } } 

然后在你的PartialView中:

@Html.EditorFor(model => model.ReturnDateForDisplay)