Show "NULL" for null values in ASP.NET MVC DisplayFor Html Helper

Splendor picture Splendor · Apr 13, 2013 · Viewed 19.5k times · Source

Is there a way to get an @Html.DisplayFor value to show "NULL" in the view if the value of the model item is null?

Here's an example of an item in my Details view that I'm working on currently. Right now if displays nothing if the value of the Description is null.

<div class="display-field">
    @Html.DisplayFor(model => model.Description)
</div>

Answer

Chtiwi Malek picture Chtiwi Malek · Jun 24, 2013

yes, I would recommend using the following data annotation with a nullable datetime field in your codefirst model :

[Display(Name = "Last connection")]
[DisplayFormat(NullDisplayText = "Never connected")]
public DateTime? last_connection { get; set; }

then in your view :

@Html.DisplayFor(x => x.last_connection)