为什么 Razor 声明性 @helper 方法中的 HtmlHelper 实例为空? [英] Why is the HtmlHelper instance null in a Razor declarative @helper method?
本文介绍了为什么 Razor 声明性 @helper 方法中的 HtmlHelper 实例为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 MVC 3 RTM 我得到一个奇怪的 NullReferenceException
:
Using MVC 3 RTM I'm getting a strange NullReferenceException
:
@helper TestHelperMethod() {
var extra = "class="foo"";
<div @Html.Raw(extra)></div>
}
结果是Html
(HtmlHelper
类型)是null
.
我以前从未在常规视图中看到过这种情况.我开始尝试在 Razor 中使用声明式辅助方法(到目前为止它们似乎有点受限),我对我在这里看到的东西感到非常困惑.
I've never seen this before in a regular view. I'm starting to experiment with declarative helper methods in Razor (so far they seem a little limited) and I'm quite stumped by what I'm seeing here.
推荐答案
这是一个已知的这些助手的限制.一种可能性是将其作为参数传递:
That's a known limitation of those helpers. One possibility is to pass it as parameter:
@helper TestHelperMethod(HtmlHelper html) {
var extra = "class="foo"";
<div@html.Raw(extra)></div>
}
另一种可能是将 helper 编写为扩展方法:
Another possibility is to write the helper as an extension method:
public static class HtmlExtensions
{
public static MvcHtmlString TestHelperMethod(this HtmlHelper)
{
var div = new TagBuilder("div");
div.AddCssClass("foo");
return MvcHtmlString.Create(div.ToString());
}
}
然后:
@Html.TestHelperMethod()
这篇关于为什么 Razor 声明性 @helper 方法中的 HtmlHelper 实例为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文