Search code examples
c#asp.netasp.net-mvcnamespaceshtml-helper

Single using statement, multiple MVC views


I've written a few extension methods (HTML helpers) and would like to use them throughout multiple views, this...

@using My.Extensions.Namespace

@Html.MyExtension()

...obviously works. But it means including the using statement in every single view (there'll be many).

If this is the only approach, that's fine, but I'm interested if there's a way of using this namespace 'globally' without declaring it in every individual view.


Solution

  • You can include it through webconfig file inside Views folder:

      <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
          <namespaces>
            ...
            <add namespace="My.Extensions.Namespace"/>
          </namespaces>
        </pages>
      </system.web.webPages.razor>
    

    Every namespace that we need to refer to in a Razor view needs to be declared either in this way or in the view itself with a @using statement.