How to import a namespace in Razor View Page?
When ae are working with asp.net mvc project we may need to create many number of namespaces which are used by different views i our project. But when we create new namespaces we have to register those namespaces so that we can use them in all our views. In this article am going to explain how we can import/add namespaces in Razor View.
If you want to import namespaces in a Razor View , you can do it in several ways like below
You can do it using @using statement which you have to write in your .cshtml page. Like
@using MyNamespace
and for VB.NET you have to write
@Imports Mynamespace
But the above method imports namespace to only current files. But if you want to add namespace to all .cshtml files then you have to register your custom namespace in web.config. (The web.config file which you will find in Views Folder).
Look for the below code in your web.config file
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
add your custom namespace to the list of namespaces in web.config
<add namespace="your.customnamespace" />
Note: When you add the above namespace in your web.config file, then that namespace is imported JUST for views in that folder.But if you want to import a namespacein an other views like area views, then you should also import that namespace, in the web.config file which is located in area's Views folder;
And in ASP.NET MVC 3, to import a namespace on all of your razor views then add the following code in Global.asax.cs
Microsoft.WebPages.Compilation.CodeGeneratorSettings.AddGlobalImport("Namespace.Namespace");
Hope this post helps you.