I have a content type that has a "Start Date and Time" field that is a Date/Time picker. Then in my C# template, I have my formatted date and time:
@Content.StartDateTime.ToString("h:mm tt")
If the field is optional and the user doesn't fill it out, the module will throw an error. To get around this, I have to make the Date/Time picker required, then use a presentation setting toggle to determine if it's shown or not. I also pre-fill the field with a date. This is ok but ideally I'd like to leave the date/time field optional sometimes.
Is there a different way to write the C# code to handle the empty fields?
In "normal" C# you could do this (but it won't work in the Razor used in DNN, which supports an older C# version:
@(Content.StartDateTime?.ToString("h:mm tt"))
So in Razor it's ca. this 😊:
@(Content.StartDateTime != null ? Content.StartDateTime.ToString("h:mm tt") : "")
See also: https://2sxc.org/dnn-tutorials/en/razor/basics210/page