1

The System.Web.UI namespace is imported by default in a Razor template.

How can I avoid this?

Alon Gubkin
  • 56,458
  • 54
  • 195
  • 288

1 Answers1

1

I'm not sure if this is what you're after, but I did a quick experiment. I think it works.

I extended the MvcWebRazorHostFactory a bit. The new factory basically passes along the host created by the base class, but removes the namespace first.

This is the class:

namespace TestCode
{
    using System.Web.WebPages.Razor;
    using System.Web.Mvc;
    using System.Web.Mvc.Razor;

    public class CustomWebRazorHostFactory : MvcWebRazorHostFactory
    {
        public override WebPageRazorHost CreateHost(string virtualPath, string physicalPath)
        {
            WebPageRazorHost host = base.CreateHost(virtualPath, physicalPath);
            host.NamespaceImports.Remove("System.Web.UI");
            return host;
        }
    }
}

Then I changed web.config to use my factory instead of the standard one:

<system.web.webPages.razor>
    <!--<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />-->
    <host factoryType="TestCode.CustomWebRazorHostFactory" />

Bingo!

Nigel Whatling
  • 2,371
  • 1
  • 16
  • 22