I've been implementing some @helper
functions in Razor based on Scott Gu's post, and things are going pretty well.
What I was wondering though, is if it's possible to call one @helper
from another. For example, I have the following helper that displays date and time for a DateTime?
:
@helper DateTimeDisplay(DateTime? date)
{
if (date.HasValue)
{
@date.Value.ToShortDateString()<br />
<text>at</text> @date.Value.ToShortTimeString()
}
else
{
<text>-</text>
}
}
This works fine, but in some situations I have other fields that are not nullable, so I tried adding this to keep things DRY:
@helper DateTimeDisplay(DateTime date)
{
DateTimeDisplay(new DateTime?(date));
}
This compiles and runs OK, but when it renders it just shows as an empty string for the non-nullable DateTime
. Here's the markup that calls the @helper
functions. Model.UpdateDate
is a regular DateTime
and Model.LastRun
is a DateTime?
...
<tr>
<td>Last updated </td>
<td class="value-field">@Helpers.DateTimeDisplay(Model.UpdateDate)</td>
</tr>
<tr>
<td>Last run </td>
<td class="value-field">@Helpers.DateTimeDisplay(Model.LastRun)</td>
</tr>
...
Is there a way to render one @helper
function by calling it from another?
You need to write @DateTimeDisplay(...)
to print the return value to the page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With