Error CS0103 The name ‘ViewBag’ does not exist in the current context

Those of you who are familiar with ASP.NET will be familiar with this sort of error, sometimes it can simply be ignored and sometimes it can’t. In this case I had a legacy application that I was updating to a more recent platform and this error cropped up quite a few times.

In my case this error appeared on quite a few pages. There are a few things that can be attempted to resolve this. Possibly the simplest is to delete the ComponentModelCache. This is in your local AppData folder. One way to get to this is type Win + R and enter %AppData% This takes you to the Roaming folder so you have to go up a level then into \Microsoft\VisualStudio\. In my case I was looking for a 16.0 folder but there were three, and the most obvious one the 16.0 one didn’t have what I was looking for. Of the two remaining ones I looked into the one with the most recent modified date and found the folder I was looking for i.e. ComponentModelCache. Normally the path will be something like

C:\Users\<your login name>\AppData\Local\Microsoft\VisualStudio\16.0\ComponentModelCache

Before you proceed you should close all instances of VS. Then you can delete the contents of that folder. VS will automatically regenerate the files when you start it up again.

In my case that resolved most but not all of the issues, however the solution would then run. The next thing I tried was checking the version of MVC. To do this I needed to look at the web.config file, which in my case was in the Views folder (Alternatively, or in case of doubt just look at the properties of the reference to System.Web.Mvc in your project.) My Web.config contained the following

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

However in the main web.config I had

<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0"/></dependentAssembly>

which matched the version in the project references as you may expect. Updating the version number in the Views web.config file didn’t resolve the issue but didn’t stop the application from running.

Bizzarely for me the issues randomly stopped a while later — I had been doing other things and when I came back there were no errors. If I ever get to the bottom of this I will post again.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Steve Ellwood

Senior Integrations Officer at Doncaster Council Any views expressed are entirely my own.