如何在 ASP.NET MVC 3 中以特定格式呈现 DateTime? [英] How to render a DateTime in a specific format in ASP.NET MVC 3?
问题描述
如果我的模型类中有一个 DateTime
类型的属性,我如何以特定格式呈现它 - 例如以 ToLongDateString()
返回的格式?
If I have in my model class a property of type DateTime
how can I render it in a specific format - for example in the format which ToLongDateString()
returns?
我已经试过了...
@Html.DisplayFor(modelItem => item.MyDateTime.ToLongDateString())
...抛出异常,因为表达式必须指向属性或字段.还有这个……
...which throws an exception because the expression must point to a property or field. And this...
@{var val = item.MyDateTime.ToLongDateString();
Html.DisplayFor(modelItem => val);
}
...它不会抛出异常,但呈现的输出是空的(尽管 val
包含预期值,正如我在调试器中看到的那样).
...which doesn't throw an exception, but the rendered output is empty (although val
contains the expected value, as I could see in the debugger).
提前感谢您的提示!
编辑
ToLongDateString
只是一个例子.我真正想要使用的而不是 ToLongDateString
是 DateTime
和 DateTime?
的自定义扩展方法:
ToLongDateString
is only an example. What I actually want to use instead of ToLongDateString
is a custom extension method of DateTime
and DateTime?
:
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
参数.
So, I think I cannot use the DisplayFormat
attribute and DataFormatString
parameter on the ViewModel properties.
推荐答案
如果您只想以特定格式显示日期,只需调用:
If all you want to do is display the date with a specific format, just call:
@String.Format(myFormat, Model.MyDateTime)
使用 @Html.DisplayFor(...)
只是额外的工作,除非您指定模板,或者需要使用基于模板的东西,例如迭代 IEnumerable<;
.创建模板非常简单,也可以提供很大的灵活性.在您的视图文件夹中为当前控制器(或共享视图文件夹)创建一个名为 DisplayTemplates
的文件夹.在该文件夹中,添加具有要为其构建模板的模型类型的局部视图.在本例中,我添加了 /Views/Shared/DisplayTemplates
并添加了一个名为 ShortDateTime.cshtml
的部分视图.
Using @Html.DisplayFor(...)
is just extra work unless you are specifying a template, or need to use something that is built on templates, like iterating an IEnumerable<T>
. Creating a template is simple enough, and can provide a lot of flexibility too. Create a folder in your views folder for the current controller (or shared views folder) called DisplayTemplates
. Inside that folder, add a partial view with the model type you want to build the template for. In this case I added /Views/Shared/DisplayTemplates
and added a partial view called ShortDateTime.cshtml
.
@model System.DateTime
@Model.ToShortDateString()
现在您可以使用以下行调用该模板:
And now you can call that template with the following line:
@Html.DisplayFor(m => m.MyDateTime, "ShortDateTime")
这篇关于如何在 ASP.NET MVC 3 中以特定格式呈现 DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!