BrunoLM
BrunoLM

Reputation: 100381

How to create HtmlHelper extensions with Razor?

I saw this syntax:

@helper IncludeJS(string url)
{
    <script src="@url" type="text/javascript"></script>
}

Placed on a .cshtml file on Views\Helpers. But then it is not recognized on views when using either:

Html.IncludeJS("")
IncludeJS("")

And I get this error:

CS1061: 'System.Web.Mvc.HtmlHelper<dynamic>' does not contain a definition for...

How can I create a custom HtmlHelper extension and use it on MVC3 (Razor)?

Upvotes: 1

Views: 2103

Answers (2)

Chris Moschini
Chris Moschini

Reputation: 37987

I got this same error because I had this:

<system.web>
    <pages>
        <namespaces>
            <add namespace="MyNamespace"/>

When I needed this:

<system.web.webPages.razor>
    <pages>
        <namespaces>
            <add namespace="MyNamespace"/>

In other words, there are multiple tags in the Web.Config in /Views, especially if you're using more view engines than Razor. You need to make sure you add this line to the Razor section if you want your HtmlHelper extensions to show up in your cshtml files.

Upvotes: 0

SLaks
SLaks

Reputation: 888185

Helpers create normal page methods, not extension methods:

@IncludeJS("")

If you want to create an Html extension method, you'll need to create a normal extension method (in a .cs file) for the HtmlHelper class.
If you do that, you can use the TagBuilder class.


EDIT: The Views\Helpers feature was dropped before RTM.

Upvotes: 1

Related Questions