0

I'm trying to do a very simple Html helper in Asp.net MVC 5:

@helper GetMyTextArea()
{
    @Html.TextArea("myText")
}

Then i try to include it in my view: (the helper is in a file called MyHelp.cshtml, located in the App_Code Folder)

@MyHelp.GetMyTextArea()

If i render my view now, i get following exception:

System.NullReferenceException: System.Web.WebPages.HelperPage.Html.get returned null.

Anyone know this issue? I think i can work around it with a partial view but this shouldn't be a problem with a html helper.

1 Answer 1

1

There are certain limitations apply when using @helper in App_Code folder, such like no direct access to standard HtmlHelper methods (you need to pass it manually by including it in your method, e.g. @helper GetMyTextArea(HtmlHelper Html)). You can add @functions which enables direct access to HtmlHelper methods:

@functions {
    public static WebViewPage page = (PageContext.Page as WebViewPage);
    public static HtmlHelper<object> html = page.Html;
}

Hence, MyHelp.cshtml content should be like this:

// adapted from /a/35269446/
@functions {
    public static WebViewPage page = (PageContext.Page as WebViewPage);
    public static HtmlHelper<object> html = page.Html;
}

@helper GetMyTextArea()
{
    @Html.TextArea("myText")
}

Afterwards, you can call the helper method in view page as @MyHelp.GetMyTextArea() without passing HtmlHelper manually.

Similar issues:

Razor: Declarative HTML helpers

Using @Html inside shared @helper in App_Code

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.