Greg Hayden
Greg Hayden

Reputation: 135

Date Format using Html.DisplayFor() in MVC5

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?

Upvotes: 6

Views: 28893

Answers (4)

Wagner DosAnjos
Wagner DosAnjos

Reputation: 6374

Have you tried this?

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

Upvotes: 1

Greg Hayden
Greg Hayden

Reputation: 135

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

Upvotes: 0

Vinney Kelly
Vinney Kelly

Reputation: 5095

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.

Upvotes: 5

abc123
abc123

Reputation: 262

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.

Upvotes: 0

Related Questions