如果我的模型类中有一个DateTime
类型的属性,我如何以特定的格式呈现它-例如,以ToLongDateString()
返回的格式呈现它?
我试过了..。
@Html.DisplayFor(modelItem => item.MyDateTime.ToLongDateString())
...which会引发异常,因为表达式必须指向属性或字段。还有这个..。
@{var val = item.MyDateTime.ToLongDateString();
Html.DisplayFor(modelItem => val);
}
...which不会抛出异常,但是呈现的输出是空的(尽管val
包含期望值,正如我在调试器中看到的那样)。
谢谢你提前给我提示!
编辑
ToLongDateString
只是一个例子。我实际上想使用的是DateTime
和DateTime?
的自定义扩展方法,而不是ToLongDateString
public static string FormatDateTimeHideMidNight(this DateTime dateTime)
{
if (dateTime.TimeOfDay == TimeSpan.Zero)
return dateTime.ToString("d");
else
return dateTime.ToString("g");
}
public static string FormatDateTimeHideMidNight(this DateTime? dateTime)
{
if (dateTime.HasValue)
return dateTime.Value.FormatDateTimeHideMidNight();
else
return "";
}
因此,我认为不能在ViewModel属性上使用DisplayFormat
属性和DataFormatString
参数。
https://stackoverflow.com/questions/6001654
复制相似问题