Import namespace globally in ASP.NET views without @using

In my ASP.NET MVC 5 application, I have all my models in a namespace MyApp.Models

. To use the model in my view eg. to show which model it should use with @model UserLoginModel

, I need to import the namespace with using MyApp.Models

.

This is not a big problem, but I would prefer to have this namespace automatically included in each of my views to avoid redundant imports across all views. I found out that the web.config file in my view folder seems to be correct for this to work.

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="MyApp" />
    <add namespace="MyApp.Models"/>
  </namespaces>
</pages>

      

But it doesn't work. This was all pre-built by Visual Studio. I only added <add namespace="MyApp.Models"/>

for my models.

On SO I found a similar question as mine but just asked that it should work using a file Views/web.config

as I tried and answears follow his question which is listed for the new ASP.NET MVC 6 beta. But I am using MVC 5.1.2 and can't get it working, it can't find the view without including the s namespace @using

in the view.

+3


source to share


1 answer


You can add namespaces globally using the new _ViewImports.cshtml. Content example:



@using Microsoft.AspNet.Identity
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

      

+1


source







All Articles