如何呈现在ASP.NET MVC 3特定格式的日期时间? [英] 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())
...它抛出一个异常,因为前pression必须指向一个属性或字段。这...
...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 "";
}
所以,我想我不能使用 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< T>
。创建模板是很简单的,并能提供很大的灵活性了。创建一个文件夹在你的看法名为电流控制器(或共享文件夹的意见)夹 DisplayTemplates
。这个文件夹里,添加你想建立模板模型类型的局部视图。在这种情况下,我加入 /查看/共享/ 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特定格式的日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!