开发者

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 w开发者_运维问答ondering 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜