Craig Craig - 1 month ago 8
C# Question

Handling logic and constants in the View

I have a date that gets displayed on my

View
that shows the last date a user logged in. They may have never done so. So it's passed as a
nullable DateTime
.

On the UI, I display it like this:

<td>@(u.LastVisit != null ? u.LastVisit.Value.ToString("dd-MMM-yyyy") : "Not yet")</td>


But I have a few issues with this and think it might be bad practice.

Firstly, the view now has logic. (If null, show "Not Yet", else show the date). The View also dictates the date format. That format is already stored as a constant in a Constants file, accessible from my controller. And the text "Not Yet" should probably be a constant as well.

The only way I can see around this, is to return a String to the UI, and move that logic to the controller. But is that the right way to do this?

Answer

You can apply a [DisplayFormat] attribute to the property and set the DataFormatString and NullDisplayText properties, for example

[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", NullDisplayText = "Not yet")]
public DateTime? LastVisit { get; set; }

If you have already defined some constants for the format then you can use (for example) DataFormatString = yourAssembly.Constants.DateFormat where DateFormat is defined as

public const string DateFormat = "{0:dd-MMM-yyyy}";

and in the view use DisplayFor()

@foreach(var u in Model)
{
    @Html.DisplayFor(m => u.LastVisit)
}