如果我的模型类中有一个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
参数。
发布于 2011-05-14 20:30:41
如果您想要以特定格式显示日期,只需调用:
@String.Format(myFormat, Model.MyDateTime)
使用@Html.DisplayFor(...)
只是额外的工作,除非你指定了一个模板,或者需要使用一些构建在模板上的东西,比如迭代IEnumerable<T>
。创建一个模板非常简单,而且可以提供很大的灵活性。在视图文件夹中为当前控制器(或共享视图文件夹)创建一个名为DisplayTemplates
的文件夹。在该文件夹中,添加一个局部视图,其中包含您想要为其构建模板的模型类型。在本例中,我添加了/Views/Shared/DisplayTemplates
并添加了一个名为ShortDateTime.cshtml
的局部视图。
@model System.DateTime
@Model.ToShortDateString()
现在,您可以使用下面的代码行调用该模板:
@Html.DisplayFor(m => m.MyDateTime, "ShortDateTime")
发布于 2011-05-14 19:57:51
您可以使用[DisplayFormat]
属性来修饰视图模型属性:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
public DateTime MyDateTime { get; set; }
在你看来:
@Html.EditorFor(x => x.MyDate)
或者,为了显示值,
@Html.DisplayFor(x => x.MyDate)
另一种可能性是,我不推荐使用弱类型的helper:
@Html.TextBox("MyDate", Model.MyDate.ToLongDateString())
发布于 2011-11-07 14:32:41
模型内部的简单格式化输出
@String.Format("{0:d}", model.CreatedOn)
或者在foreach循环中
@String.Format("{0:d}", item.CreatedOn)
https://stackoverflow.com/questions/6001654
复制相似问题