The name 'ViewBag' does not exist in the current context - Visual Studio 2015
I accidentally removed web.config
from the Views
folder, thinking that it was unnecessary. When I put it back it started working.
I had this issue despite having all the correct configuration.
It turned out to be some bad files in the Component Cache, preventing the Razor views from recognising ViewBag, Model, and HtmlHelpers. Deleting these files solved the problem (good versions of these files were created next time I opened Visual Studio).
The files are located here:
%LOCALAPPDATA%\Microsoft\VisualStudio\14.0\ComponentModelCache
Delete all four files:
- Microsoft.VisualStudio.Default.cache
- Microsoft.VisualStudio.Default.catalogs
- Microsoft.VisualStudio.Default.err
- Microsoft.VisualStudio.Default.external
I have subsequently seen the same issue on several other developer machines and this fix quickly solves it.
Update the version numbers in the settings of the web.config
file in the Views folder.
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
If you have updated the MVC version through nuget, should be:
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
Other dependency versions might need to be updated too. Compile and namespace issues in Views for MVC helpers and objects are typically related to messed up web.config
files within the View folders.
Find "webpages:Version" in the appsettings and update it to version 3.0.0.0. My web.config had
<add key="webpages:Version" value="2.0.0.0" />
and I updated it to
<add key=”webpages:Version” value=”3.0.0.0″ />