简体   繁体   中英

How do I use the C# Global namespace operator with a using directive in my View?

Having some trouble with my view in asp.net mvc. My using directive's namespace is clashing with the namespace of the view, causing compile errors in my Razor generated class. I had the same issue with the @model directive, but using the global:: alias fixed it. For some reason, doing the same on my @using causes a "The type or namespace 'global' could not be found..." error. Here is what I have right now:

@using SampleSpace.System.Items

@model global::SampleSpace.System.Items.Thing

I want to use

@using global::SampleSpace.System.Items

@model global::SampleSpace.System.Items.Thing

But the aforementioned error keeps occurring. Is there any trick to using global in a using directive in a view, or is there a reason it isn't allowed?

I'm not sure if this exactly answers your question, but could you resolve the issue by putting the namespace you're interested in in the web.config of your Views folder?

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

This is generally good practice where your views need to "use" a namespace - it keeps clutter out of the view itself - I haven't tested this in the conflict scenario you've described though.

Or fall back on this approach to avoid conflicts:

@using items = SampleSpace.System.Items

Hope that's helpful.

Turns out the simplest way to overcome this is to adjust the Custom Tool Namespace under the files Properties. You can change this to whatever you'd like to avoid any conflicts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM