Namespace issue with MVC view - Razor engine

2019-04-09 10:31发布

问题:

I added reference to the System.Web.DataVisualization to my MVC project. Now when I try to add the namespace to my web.config I am getting error

CS0234: The type or namespace name 'DataVisualization' does not exist in the namespace 'System.Web.UI' (are you missing an assembly reference?)

So then I try to use the same in my controller. This works perfectly.

using System.Web.UI.DataVisualization;

Then the same should work in my Razor view

So I try to use this in my Razor view

@using System.Web.UI.DataVisualization;

This again not not work giving me the same error

How come I can use the namespace in my controller and not in my views?

Am I missing something...

回答1:

If you go to the project references, go to properties on "System.Web.DataVisualization," then set "CopyLocal" to true, you'll then be able to put

@using System.Web.UI.DataVisualization

in your Razor view.



回答2:

This made me curious so I just tried it myself. It works fine. Make sure you add your namespace to the Web.Config in the 'Views' folder (not the root 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="System.Web.UI.DataVisualization.Charting" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>