How do I import a namespace in Razor View Page? How do I import a namespace in Razor View Page? asp.net asp.net

How do I import a namespace in Razor View Page?


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.


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/


For Library

@using MyNamespace

For Model

@model MyModel