In my case I had this issue happening only on my PC only for one project. My project worked fine in VS2012 but when opened in VS2017 it was having this problem.
The main issue for me here was cache. My project was pointing to the older cached versions of dll for Razor and MVC and it was not finding features that were added in newer versions, such as ViewBag. ViewBag was added in Razor version 3, but because I had Razor version 2 cached it could not find ViewBag (but it could find other stuff which were present in version 2). However, simply clearing cache like in the accepted answer did not fix my problem. We had to change config files to say "use version 3 instead of 2" for Razor and "use version 5 instead of 4" for MVC, then closing VS, removing cache, and opening project and rebuilding. Then things got fixed. Below are more detailed instructions.
Here is the sequence of changes that helped me fix my problem:
- In "Views" folder's Web.config change all locations where
- MVC version is set to 4.0.0.0 to 5.0.0.0
- Razor version is set to 2.0.0.0 to 3.0.0.0
Here are those lines in my case:
<sectionGroup name="system.web.webPages.razor" type="... Version=3.0.0.0 ...">
<section name="host" type="... Version=3.0.0.0 ..." .../>
<section name="pages" type="... Version=3.0.0.0 ..." .../>
</sectionGroup>
...
<host factoryType="... System.Web.Mvc, Version=5.0.0.0 ..." />
...
<pages
...
pageParserFilterType="... Version=5.0.0.0 ..."
pageBaseType="... Version=5.0.0.0 ..."
userControlBaseType="... Version=5.0.0.0 ...">
<controls>
<add assembly="... Version=5.0.0.0 ..." ... />
</controls>
</pages>
(notes: 1) your versions may be different, I am just telling what needed to be done in my case 2) I omitted some stuff with "..." for brevity 3) even if you have MVC version something like 5.3.2.0 you should still input 5.0.0.0, same with Razor's version - input all zeros in 3.0.0.0)
In main config file (the one at the top level) change webPages:version
from 2.0.0.0 to 3.0.0.0.
This change probably did not affect solution but I'll still mention it. Make sure that "Views" folder's <namespaces>
section has the exact same contents as main .conifg file at the root of the project, something like:
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
- Finally, close VS. Delete all cache files in
%LOCALAPPDATA%\Microsoft\VisualStudio\14.0\ComponentModelCache
(or whatever your correct path is) just like it is suggested in (currently) accepted answer by Fenton. Also delete .scan
file, even if it is not mentioned in that answer. Once you are done, open VS, Clean your project and Rebuild it. Things should be working now. It worked for me.