When you want use your own code generating classes like HtmlHelpers in a Razor view, you can register the namespace at the beginning of the Razor view like this:
@using My.Custom.Namespace
But what when you want to use a certain class in almost all of your views? Well, of course you can manually add the using statement to each view, but there is another way. You can add the namespace in your Web.Config file. The catch here is that you don’t need to add it to the Web.Config file in the root of your project, but to the Web.Config file in the View directory.
Just add it to this part of the file:
<system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <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" /> <add namespace="My.Custom.Namespace" /> </namespaces> </pages> </system.web.webPages.razor>
Thanks for this tidbit. I’ve added a namespace for a third party assembly that’s definitely referenced in my app, but it’s still saying the namespace can’t be found at render time. Are there other attributes I need to set to ensure the assembly gets added?
John – Adding the full namespace to Web.Config in your Views folder should be enough. Let’s say you have the following extension method for the HtmlHelper:
namespace My.Custom.Namespace
{
public class MyExtensionMethods
{
public static string SayHello(this HtmlHelper html, string name)
{
return String.Format("Hello there, {0}!", name);
}
}
}
To use it in your Razor views, you have to add the full namespace to your Web.Config:
<add namespace="My.Custom.Namespace" />Now I can use it like this in my Razor view:
@Html.SayHello("John")Hope this helps.