anaximander
anaximander

Reputation: 7140

Using enum in @Url.Action() routevalues

This question is just a quick one. I have a set of links on a page, and they all actually point to the same controller method - the difference between them is that they each pass a different value to that method so that the subsequent process is slightly different. I happened to already have an enum defined to correspond to the possible values passed, so without thinking, I did this:

@Url.Action("QueryStepTwo", new { type = QueryType.UserRecords })

and was pleasantly surprised to see that nothing gained a red underline. I hit compile and navigated to that page to verify, to be presented with an error message for CS0103: "The name 'QueryType' does not exist in the current context". In the editor, QueryType is syntax-highlighted and IntelliSense provides the options list when I type it.

I'm assuming this is just a case of VS/IntelliSense being just a little bit too smart and knowing things that the actual page parse/render engine can't? Casting the enum to its string or int value doesn't help, so I'm guessing this is to do with the order in which things are executed; more specifically, the enum is out of scope by the time Razor gets to see the page. Is there a way to use an enum in URL helpers like this, especially one that doesn't require the enum to be defined as a member of the view model? I dislike using magic strings all over the place; they're too vulnerable to typos and tomfoolery.

Upvotes: 0

Views: 2045

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

Make sure you fully qualify the namespace where this enum is defined:

@Url.Action("QueryStepTwo", new { type = SomeNamespace.QueryType.UserRecords })

or if you don't want to do that you could also add an @using directive to the top of your Razor view:

@using SomeNamespace

And if you want to do this globally for all Razor views you could add this namespace to the <namespaces> node in ~/Views/web.config (not to be confused with ~/web.config):

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <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="SomeNamespace" />
      </namespaces>
    </pages>
</system.web.webPages.razor>

As far as the Intellisense in Razor views is concerned, this is not something that could be trusted. Hopefully Microsoft will improve it in future versions.

Upvotes: 2

Related Questions