784

How to import a namespace in Razor View Page?

Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
Amitabh
  • 59,111
  • 42
  • 110
  • 159
  • 6
    You can also add alias to your imported namespace http://stackoverflow.com/questions/4798293/mvc3-import-namespace/8043480#8043480 – Surjit Samra Nov 14 '11 at 13:54

11 Answers11

897

Finally found the answer.

@using MyNamespace

For VB.Net:

@Imports Mynamespace

Take a look at @ravy amiry's answer if you want to include a namespace across the app.

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
Amitabh
  • 59,111
  • 42
  • 110
  • 159
  • 8
    Also: They can't go in code blocks. (You'll get a runtime error) – Dan Esparza Jul 24 '11 at 03:31
  • 6
    Also you don't need the semicolon. – RPM1984 Jul 25 '11 at 23:34
  • hi, how to use globalization in view in mvc, as mentioned [here](http://stackoverflow.com/a/8744037/2218697) ? – Shaiju T Mar 31 '15 at 09:04
  • 6
    This is just bad practice period. Please do not add this to the top of your razor pages. This is messy etc... Correct way is to add to Views - web.config just as @Javad_Amiry points out. – Tom Stickel Aug 03 '15 at 20:54
  • 30
    It's not bad practice. It's an absolutely necessary feature. web.config is like a global using statement that makes the namespace active in ALL your pages. That may not be what you want if you have classes with the same name in different namespaces. You'll still have a conflict if you try to use them in the same file, but you can resolve that easily within a single file. If you stick it in web.config, then the conflict would arise in all your pages that use either of the classes. So calling this bad practice makes no sense at all. – Triynko Sep 04 '15 at 22:15
  • 5
    I'm surprised Intellisense doesn't hint to add the using statement the same way it does in normal C# pages. – Triynko Sep 04 '15 at 22:15
  • @Triynko It may not be a _bad_ practice, based on the valid examples you provided, however without those conflicts, this definitely isn't the _best_ practice. – krillgar Nov 18 '16 at 12:31
  • What if it's narrowed down to not using Imports Mynamespace at all and only use it within the view where necessary? For example, If Mynamespace.objClass Then... without Imports, instead of If objClass Then.... with Imports.Mynamespace. – JoshYates1980 May 30 '17 at 15:00
413

The first way is that use @using statement in .cshtml files, that imports a namespace to current file only, and the second:

In the "web.config" file in "Views" directory of your project (notice it is not the main web.config in project's root), find this section:

<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      .
      .
      <!-- etc -->
    </namespaces>
  </pages>
</system.web.webPages.razor>

you can add your custom namespace like this:

<add namespace="My.Custom" />

that will add the namespace to all of .cshtml (and/or .vbhtml) files; also you can change views inheritance from here, like:

<pages pageBaseType="My.Custom.MyWebViewPage">

Regards.


UPDATE: Thanks to @Nick Silberstein to his reminder about areas! He said:

If you're working within an area, you must add the namespace within the Web.config under /Areas/<AreaName>/Views/ rather than /Views/

amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • I don't have that section in my web.config, should I add it? – vtortola Jul 21 '11 at 11:30
  • 11
    @vtortola : which web.config? the web.config file in Views folder, not the main web.config in root folder. ok? – amiry jd Jul 21 '11 at 13:37
  • 11
    I'd like to hopefully save someone a few minutes of pulling out their hair and say that if you're working within an area, you must add the namespace within the Web.config under /Areas/Views/ rather than /Views/. – Nick Silberstein Nov 11 '11 at 01:03
  • 12
    @MatthijsWessels No it does not need to restart VS. Just build the project and it will take effect. At least I do this always. If a view is open, you have to close that view before build and re-open it after after build. – amiry jd Dec 28 '12 at 14:23
  • 2
    @Javad_Amiry, aha, I did rebuild, but didn't close the view. – Matthijs Wessels Dec 28 '12 at 15:24
  • Using the web.config method of importing prevents polluting views with too many implementation details, like which implementation of a class to use. This assumes two implementations would share the same name but have different namespaces. You could shoehorn in a test-only implementation by using web.config transformations, and a `blah.blah.test` namespace. – Greg Jun 19 '15 at 17:30
  • 1
    Yes, this is the correct way. Not the Using statement at top of Razor page like in the OP selected answer.... – Tom Stickel Aug 03 '15 at 20:55
  • Regardless of what Microsoft intended, I consider coding through config files a bad practice -- configs should be for system 'where do I find stuff', or simple parameter changes. I'm surprised that xxx.models and xxx.controllers -- etc doesn't just work, since MVC is based on that kind of magic configuration. – Gerard ONeill Jul 26 '17 at 14:45
33

For Library

@using MyNamespace

For Model

@model MyModel
Alper Şaldırak
  • 1,034
  • 8
  • 10
  • 1
    Why is there no ; at the end? – FrenkyB Nov 08 '16 at 06:30
  • 2
    @FrenkyB because this isn't C# code, it's Razor code. The `using` at the beginning of a .cs file is a C# compiler keyword. The `@using` at the beginning of a .cshtml file is a hint to the Razor template engine. – Mark Aug 09 '17 at 23:11
27

In ASP.NET MVC 3 Preview1 you can import a namespace on all your razor views with this code in Global.asax.cs

Microsoft.WebPages.Compilation.CodeGeneratorSettings.AddGlobalImport("Namespace.Namespace");

I hope in RTM this gets done through Web.config section.

Germán
  • 1,183
  • 8
  • 11
  • 6
    There will be a web.config section in RTM, but we also wanted to provide an API to do this because many users are starting to gravitate away from config. So we have both options available for you! – Andrew Stanton-Nurse Jul 30 '10 at 18:23
  • 6
    As of ASP.NET MVC 3 Beta this method no longer works. There is a new web.config section as explained here http://stackoverflow.com/questions/3875207/razor-syntax-using-and-namespace-declarations-fail . The AddGlobalImport method for importing a global namespace to all views has been moved to this class System.Web.WebPages.Razor.WebPagesRazorHost – Germán Oct 07 '10 at 22:20
16

I found this http://weblogs.asp.net/mikaelsoderstrom/archive/2010/07/30/add-namespaces-with-razor.aspx which explains how to add a custom namespace to all your razor pages.

Basically you can make this

using Microsoft.WebPages.Compilation;
public class PreApplicationStart
{
   public static void InitializeApplication()
   {
       CodeGeneratorSettings.AddGlobalImport("Custom.Namespace");
   }
}

and put the following code in your AssemblyInfo.cs

[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "InitializeApplication")]

the method InitializeApplication will be executed before Application_Start in global.asax

k-dev
  • 1,657
  • 19
  • 30
  • 4
    This is actually a rather good answer, but the location of `Microsoft.WebPages.Compilation.AddGlobalImport` was changed to `System.Web.WebPages.Razor.WebCodeRazorHost.AddGlobalImport`. – jahu Jul 02 '14 at 09:49
  • 2
    The big advantage of using this method comes from the fact that the namespace will be usable in all views (including those within areas) while being declared in just one place. – jahu Jul 02 '14 at 10:10
14

One issue that you must know is that when you import a namespace via web.config in Views folder, that namespace is imported JUST for views in that folder. Means if you want to import a namespace in an area views, you must also import that namespace, in that area's web.config file, located in area's Views folder;

11

For namespace and Library

@using NameSpace_Name

For Model

@model Application_Name.Models.Model_Name 

For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)

@model List<Application_Name.Models.Model_Name>

@foreach (var item in Model)
   {  
          <tr>
                <td>@item.srno</td>
                <td>@item.name</td>
         </tr>  
   }
Mahaveer Jangid
  • 366
  • 2
  • 11
10

You can try this

@using MyNamespace
Abhishek Siddhu
  • 577
  • 6
  • 22
3

"using MyNamespace" works in MVC3 RTM. Hope this helps.

Howard
  • 47
  • 1
2

I think in order import namespace in razor view, you just need to add below way:

@using XX.YY.ZZ
jarlh
  • 42,561
  • 8
  • 45
  • 63
0

Depending on your need you can use one of following method:

Imran Javed
  • 11,779
  • 2
  • 16
  • 17