ASP.NET MVC - 从另一个 @helper 调用 Razor @helper
我一直在 Razor 中基于 Scott Gu 的帖子,一切进展顺利。
不过,我想知道是否可以从另一个 @helper 调用一个 @helper
。例如,我有以下帮助程序,用于显示 DateTime?
的日期和时间:
@helper DateTimeDisplay(DateTime? date)
{
if (date.HasValue)
{
@date.Value.ToShortDateString()<br />
<text>at</text> @date.Value.ToShortTimeString()
}
else
{
<text>-</text>
}
}
这工作正常,但在某些情况下,我有其他不可为空的字段,因此我尝试添加它以保留内容DRY:
@helper DateTimeDisplay(DateTime date)
{
DateTimeDisplay(new DateTime?(date));
}
编译并运行正常,但在渲染时,它仅显示为不可为 null 的 DateTime
的空字符串。以下是调用 @helper
函数的标记。 Model.UpdateDate
是常规 DateTime
,而 Model.LastRun
是 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>
...
有没有办法渲染一个@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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要编写
@DateTimeDisplay(...)
来将返回值打印到页面。You need to write
@DateTimeDisplay(...)
to print the return value to the page.