在MVC5中使用Html.DisplayFor()的日期格式 [英] Date Format using Html.DisplayFor() in MVC5
问题描述
在此帖子中引用答案我添加了/ Views / Shared / DisplayTemplates和添加了一个名为ShortDateTime.cshtml的部分视图,如下所示:
@model System.DateTime
@ Model.ToShortDateString( )
当模型包含值可以正常工作,格式化日期正确显示时:
@ Html.DisplayFor(modelItem => item.BirthDate,ShortDateTime)
pre>
但是,如果返回空值,则抛出System.InvalidOperationException。指示:
{传入字典的模型项目为空,但该字典需要一个类型为系统的非空模型项目.DateTime'。}
我的第一个倾向是在部分视图中使用if语句,但似乎并不重要。没有引用模板,空值处理如下:
@ Html.DisplayFor(modelItem => item.BirthDate)
但格式化的原始问题仍然存在。当我尝试在View中放置条件格式化时,它不起作用,但我希望它只是一个语法。
@ Html.DisplayFor(modelItem => item.BirthDate == null)? string.Empty:(modelItem => item.BirthDate,ShortDateTime))
上述结果在不同的'System.InvalidOperationException'中:
{模板只能用于字段访问,属性访问,单维数组索引,或单参数自定义索引器表达式。}
那么,有没有办法在视图中进行条件格式化来生成DateTime值的日期?
解决方案您遇到的问题是您正在传递一个
null
值转换为不可空模型。将部分视图的模型更改为DateTime?
。例如:@model DateTime?
@if(!Model.HasValue)
{
< text>< / text>
}
else
{
@ Model.Value.ToShortDateString()
}
希望这有帮助。
Referencing the answer in this post I added /Views/Shared/DisplayTemplates and added a partial view called ShortDateTime.cshtml as shown below:
@model System.DateTime @Model.ToShortDateString()
When the model contains a value this works and the formatted date is displayed correctly:
@Html.DisplayFor(modelItem => item.BirthDate, "ShortDateTime")
However, if a null value is returned a 'System.InvalidOperationException' is thrown. Indicating:
{"The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'."}
My first inclination was to use an if statement inside the partial view but it didn't seem to matter. Without referencing the template null values are handled as in:
@Html.DisplayFor(modelItem => item.BirthDate)
but the original issue of formatting remains. When I try to put conditional formatting in the View as follows, it doesn't work but I hoping it's just a syntax thing.
@Html.DisplayFor(modelItem => item.BirthDate == null) ? string.Empty : (modelItem => item.BirthDate, "ShortDateTime"))
The above results in a different 'System.InvalidOperationException':
{"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."}
So, is there a way to do conditional formatting in the View to generate just the date from a DateTime value?
解决方案The problem you're experiencing is that you are passing a
null
value into a non-nullable model. Change the partial view's model toDateTime?
. For example:@model DateTime? @if (!Model.HasValue) { <text></text> } else { @Model.Value.ToShortDateString() }
Hope this helps.
这篇关于在MVC5中使用Html.DisplayFor()的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!