Search code examples
razorweb-configstatic-classes

Web.config equivalent to “using static MyClass;” in <add namespace=“MyClass” />


In ASP.Net, you can add a namespace to all Razor views by adding the following code to the View folder’s Web.config:

<system.web.webPages.razor>
    <namespaces>
        <add namespace=“MyClass” />
    </namespaces>
</system.web.webPages.razor>

This is equivalent to putting the statement “using MyClass;” at the top of a C# file.

However, how would I add a namespace to Web.config as a “static” class, where I can access the class’s methods directly within views without having to write out “MyClass.MyMethod();” for example?

You can already do this by putting the statement “using static MyClass;” at the top of a C# file (C# 6 is required, see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-static).


Solution

  • It just appends whatever it is you put as namespace. Just needs to append the static keyword to the namespace.

    So as you pointed out <add namespace=“MyClass” /> is equivalent to using MyClass;

    Change to <add namespace=“static MyClass” />, which is equivalent to using static MyClass;

    In your case:

    <system.web.webPages.razor>
        <namespaces>
            <add namespace=“static MyClass” />
        </namespaces>
    </system.web.webPages.razor>
    

    should be what you're looking for