Is there a way to do an `extern alias` inside a razor (MVC3) view?
Asked Answered
M

2

10

Is there a way to do an extern alias inside a razor (MVC3) view?

I have two versions of the same assembly (i.e. 1.0 and 2.0) with a type that has the same name and namespace and I need a way to specify the newer one in the razor view.

I've tried:

@extern

and:

@{ extern alias MyAlias; }

But neither of those worked.

Mopboard answered 30/10, 2012 at 22:13 Comment(1)
It can't #17823842Transnational
N
0

More than ten years later, but I did find a solution. There is still no "true" extern alias in Razor, but C# 10 did introduce global using, which together with namespace aliases can be used as a workaround.

Technically, the statement go anywhere, but the entry point of the application is the most natural place to put it. So, in Program.cs or App.cs or the equivalent, at the top of the file put

extern alias MyAlias;
global using __MyAlias = MyAlias::My.Alias;

Now, all C# files, including files auto-generated by Razor, will be able to use __MyAlias in place of MyAlias::My.Alias. Unfortunately, a using alias can't then be used in a new using statement, so you'll have to do this with every fully-qualified-namespace in the colliding assembly.

The other alternative is to split your C# code from your .razor file into a separate .razor.cs file, where you can use C# normally; but this won't let you import components from an aliased assembly.


Unfortunately, I have to retract this answer, as upon further testing it only appeared to fix the issue. In particular, it doesn't in fact extend to component .razor files, which are the most crucial. (In all other cases we can just make a code-behind file and use extern alias normally). Perhaps this false start might help someone else find a solution, so I'm leaving it up.

Nullify answered 2/2, 2024 at 7:36 Comment(0)
M
-1

In the "web.config" file in "Views" directory of your project.Find this section.

<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      .
      .
      <!-- etc -->
    </namespaces>
  </pages>
</system.web.webPages.razor>

you can add your custom namespace like this:

<add namespace="My.Custom" />

That will add the namespace to all of Razor(.cshtml or .vbhtml) files.

Memling answered 1/11, 2013 at 7:37 Comment(1)
This is not what he's asking. He wants an alias. Doing what you suggest would have the same result as @using My.Custom in the view itself.Extender

© 2022 - 2025 — McMap. All rights reserved.