Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - calling Razor @helper from another @helper

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&nbsp;updated&nbsp;</td>
    <td class="value-field">@Helpers.DateTimeDisplay(Model.UpdateDate)</td>
</tr>
<tr>
    <td>Last&nbsp;run&nbsp;</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?

like image 968
ataddeini Avatar asked May 19 '11 14:05

ataddeini


1 Answers

You need to write @DateTimeDisplay(...) to print the return value to the page.

like image 113
SLaks Avatar answered Sep 30 '22 07:09

SLaks