15

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?

4

1 回答 1

27

您需要编写@DateTimeDisplay(...)以将返回值打印到页面。

于 2011-05-19T14:33:27.720 回答