Stofa
Stofa

Reputation: 25

Issue with TextArea inside asp.net MVC 5 Html helper

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.

Upvotes: 0

Views: 183

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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

Upvotes: 1

Related Questions