Search code examples
c#asp.net-mvcasp.net-mvc-3razor

Defining an alias for a class with Razor


In a normal C# code I can use a using statement to define an alias for a class name, e.g.

using MyAlias = Some.Long.Namespace.Class;

I have tried the same in a razor view, a naive approach like

@using MyAlias = Some.Long.Namespace.Class

does not work. Is there any way to achieve the same effect ?


Solution

  • Why would you want to do that? Whatever reason you need this for, there's probably a better way. You should avoid writing C# code in a Razor view anyway, so you shouldn't need it. All you need in a Razor view is the namespace for your view model because that's all that a view should manipulate.

    @model MyViewModel
    ...
    

    Leave the aliases and C# code to where they belong - controllers, models, helpers, ...

    All this being said, the aliases should work. For example the following view runs perfectly fine for me:

    @using foo = System.IO;
    <div>
        @foo.Path.GetFileName(@"c:\work\foo.txt")
    </div>