Make sure namespaces will be imported into every view when using ASP.NET MVC 3.0 Preview 1
using System.Configuration;
using System.Web.Configuration;
using Microsoft.WebPages.Compilation;
namespace Infrastructure.Configuration
{
public static class PreApplicationStartCode
{
public static void ImportNamespace()
{
var pagesSection = ConfigurationManager.GetSection("system.web/pages") as PagesSection;
if (pagesSection == null)
return;
foreach (NamespaceInfo namespaceToImport in pagesSection.Namespaces)
{
CodeGeneratorSettings.AddGlobalImport(namespaceToImport.Namespace);
}
}
}
}
How to use the code:
Add the following code into the assembly containing the above code:
[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "ImportNamespace")]
It will make sure ASP.NET 4.0 will make a call to the ImportNamesapce method long before Application_Start is called, read more about it
here.
Make sure your ASP.NET MVC project adds a reference to the project where the above code is added to.
Now you can do use the pages/namespace section in web.config to globally import namespaces into the views. Example of the section in web.config:
<system.web>
<pages>
<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="Infrastructure.WebHelpers"/>
</namespaces>
</pages>
</system.web>
Note: The above solution will add Web Form namespaces too because it will take the namespaces added to the global configuration files.
Fork
Make sure the web.config pages/namespace can be used together with ASP.NET MVC 3 P1 and Razor - @fredrikn Wednesday 04, 2010 11:18 AM
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


770
0




Mark '.net' tag as 'like'
Mark '.net' tag as 'ignore'