为什么在剃刀声明@helper方法HtmlHelper的实例为空? [英] Why is the HtmlHelper instance null in a Razor declarative @helper method?

查看:232
本文介绍了为什么在剃刀声明@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 )的

我以前从来没有在常规视图看到了这一点。我开始尝试在剃刀(到目前为止,他们似乎有点有限的)声明辅助方法,我很被我所看到的在这里难住了。

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.

推荐答案

这是一个<一href="http://stackoverflow.com/questions/4451287/razor-declarative-html-helpers/4453637#4453637">known这些助手的限制的。一种可能是把它作为参数:

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>
}

另一种可能性是写的助手作为扩展方式:

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()

这篇关于为什么在剃刀声明@helper方法HtmlHelper的实例为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆