在 MVC5 中使用 Html.DisplayFor() 的日期格式 [英] Date Format using Html.DisplayFor() in MVC5

查看:56
本文介绍了在 MVC5 中使用 Html.DisplayFor() 的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用此 post 中的答案 我添加了/Views/Shared/DisplayTemplates 和添加了一个名为 ShortDateTime.cshtml 的局部视图,如下所示:

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")

但是,如果返回空值,则会引发System.InvalidOperationException".表示:

However, if a null value is returned a 'System.InvalidOperationException' is thrown. Indicating:

{"传入字典的模型项为空,但此字典需要'System.DateTime'类型的非空模型项."}

{"The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'."}

我的第一个倾向是在局部视图中使用 if 语句,但这似乎并不重要.不引用模板空值的处理方式如下:

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"))

以上结果导致不同的System.InvalidOperationException":

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."}

那么,有没有办法在 View 中进行条件格式设置以仅从 DateTime 值生成日期?

So, is there a way to do conditional formatting in the View to generate just the date from a DateTime value?

推荐答案

您遇到的问题是您将 null 值传递给不可为空的模型.将局部视图的模型更改为 DateTime?.例如:

The problem you're experiencing is that you are passing a null value into a non-nullable model. Change the partial view's model to DateTime?. For example:

@model DateTime?          
@if (!Model.HasValue)
    {
    <text></text>
}
else
{
    @Model.Value.ToShortDateString()
}

希望这会有所帮助.

这篇关于在 MVC5 中使用 Html.DisplayFor() 的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆