Search code examples
asp.net-mvc-3extension-methodsrazorhtml-helper

Razor HtmlHelper Extensions (or other namespaces for views) Not Found


I don't know if this was happening in the PR or Beta, but if I create an extension method on HtmlHelper, it is not recognized in a Razor powered page:

namespace SomeNamespace.Extensions {
    public static class HtmlExtensions {
        public static string Foo(this HtmlHelper html) {
            return "Foo";
        }
    }
}

I added it to the <Namespaces> section in Web.config:

<pages>
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <!-- snip -->
    <add namespace="SomeNamespace.Extensions"/>
  </namespaces>
</pages>

But it throws a compile error when trying to view the page:

@Html.Foo()

If I recreate the page with WebForms it works fine. What's the deal?

Workaround

If I include @using SomeNamespace.Extensions in my Razor view, then it works, but I'd much rather just have it in Web.config


Solution

  • Since the Beta, Razor uses a different config section for globally defining namespace imports. In your Views\Web.config file you should add the following:

    <configSections>
      <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      </sectionGroup>
    </configSections>
    
    <system.web.webPages.razor>
      <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
          <add namespace="System.Web.Mvc" />
          <add namespace="System.Web.Mvc.Ajax" />
          <add namespace="System.Web.Mvc.Html" />
          <add namespace="System.Web.Routing" />
          <!-- Your namespace here -->
        </namespaces>
      </pages>
    </system.web.webPages.razor>
    

    Use the MVC 3 upgrade tool to automatically ensure you have the right config values.

    Note that you might need to close and reopen the file for the changes to be picked up by the editor.