Date Format using Html.DisplayFor() in MVC5

被刻印的时光 ゝ 提交于 2020-01-11 02:47:24

问题


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?


回答1:


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()
}

Hope this helps.




回答2:


Have you tried this?

@if (modelItem.BirthDate != null) { Html.DisplayFor(modelItem => item.BirthDate, "ShortDateTime") }



回答3:


I guess you should declare the BirthDate property as nullable in model class

public DateTime? BirthDate{ get; set; }

and you must have declared as

public DateTime BirthDate{ get; set; }

this will expect a value every time.

if you set as nullable it will not expect a value.




回答4:


By applying the conditional statement ahead of the Html helper, only non null values get passed.

@if (item.BirthDate != null) { @Html.DisplayFor(modelItem => item.BirthDate , "ShortDateTime")}


来源:https://stackoverflow.com/questions/19920603/date-format-using-html-displayfor-in-mvc5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!