Why is the HtmlHelper instance null in a Razor declarative @helper method?

前端 未结 6 1520
余生分开走
余生分开走 2020-12-15 15:22

Using MVC 3 RTM I\'m getting a strange NullReferenceException:

@helper TestHelperMethod() {
    var extra = \"class=\\\"foo\\\"\";
    
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 15:56

    That's a known limitation of those helpers. One possibility is to pass it as parameter:

    @helper TestHelperMethod(HtmlHelper html) {
        var extra = "class=\"foo\"";
        
    }

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

    and then:

    @Html.TestHelperMethod()
    

提交回复
热议问题