Dejas
Dejas

Reputation: 3621

NRE when using Html.Encode within @helper

When invoking this helper from another cshtml I get a Null Pointer Exception on the encode line.

@helper ShowDefinitionText(String text)
{    
    <b>Definition:</b>
    <p>
    @Html.Encode("dogs")
    </p>
}

Is it not legal to use an Html.* from within a helper?

Thanks.

Upvotes: 1

Views: 231

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038940

You need to pass it as argument:

@helper ShowDefinitionText(String text, HtmlHelper htmlHelper)
{    
    <b>Definition:</b>
    <p>
        @htmlHelper.Encode("dogs")
    </p>
}

and when invoking the helper from the view provide a valid instance:

@ShowDefinitionText("some text", Html)

Also if you are only going to HTML encode you probably don't need a helper as the @ Razor operator already does this:

@helper ShowDefinitionText(String text)
{    
    <b>Definition:</b>
    <p>
        @text
    </p>
}

Upvotes: 4

Related Questions