tco*_*ode 13 datetime razor asp.net-mvc-3
我正在使用Razor Views开发ASP.Net MVC 3 Web应用程序.我有以下ViewModel,它传递给我的Razor View并迭代以显示记录列表.
视图模型
public class ViewModelLocumEmpList
{
public IList<FormEmployment> LocumEmploymentList {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
视图
<table>
<tr>
<th>Employer</th>
<th>Date</th>
</tr>
@foreach (var item in Model.LocumEmploymentList) {
<tr>
<td>@item.employerName</td>
<td>@item.startDate</td>
</tr>
}
</table>
Run Code Online (Sandbox Code Playgroud)
我的问题是这条线
@Html.DisplayFor(modelItem => item.startDate)
Run Code Online (Sandbox Code Playgroud)
返回这样的日期20/06/2012 00:00:00,我希望它删除时间,只显示日期,即20/06/2012.
我试过添加
@Html.DisplayFor(modelItem => item.startDate.Value.ToShortDateString())
Run Code Online (Sandbox Code Playgroud)
和
DisplayFor(modelItem => item.startDate.HasValue ? item.startDate.Value.ToShortDateString(): "")
Run Code Online (Sandbox Code Playgroud)
但是,它们都在运行时返回以下错误消息
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Run Code Online (Sandbox Code Playgroud)
我在这里看了Darin Dimitrov的回答使用razor转换DateTime格式
但是,我无法访问ViewModel中的startDate属性,我的ViewModel返回一个Formistmployment对象的IList,您可以在上面看到它.
如果有人对如何从日期时间属性中删除时间有任何想法,那么我将非常感激.
谢谢.
另外,我的startDate属性是Nullable.
更新
基于PinnyM的答案,我添加了一个局部类(见下文),将[DisplayFormat]属性放在startDate属性上.
public partial class FormEmployment
{
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<System.DateTime> startDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是,我的Razor View仍然使用以下代码显示20/06/2012 00:00:00
@Html.DisplayFor(modelItem => item.startDate)
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
谢谢.
pol*_*ata 27
您可以使用 @item.startDate.Value.ToShortDateString()(为null值添加适当的验证)
您可以在模型属性上使用DisplayFormat属性startDate:
[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
public DateTime? startDate { get; set; }
Run Code Online (Sandbox Code Playgroud)
正当使用 DisplayFor(modelItem => item.startDate)
另一个选项是为格式化创建只读属性:
public String startDateFormatted { get { return String.Format("{0:dd/MM/yyyy}", startDate); } }
Run Code Online (Sandbox Code Playgroud)
并使用 DisplayFor(modelItem => item.startDateFormatted)