Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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.

like image 157
Farhad Jabiyev Avatar answered Feb 17 '26 11:02

Farhad Jabiyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!