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

Sounds like you’re missing the following in the Web.Config in the views folder:

/Views/Web.Config

<?xml version="1.0"?>

<configuration>

  <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"> // <-- this line and contents are important
        <namespaces>
          <add namespace="System.Web.Mvc" />
          <add namespace="System.Web.Mvc.Ajax" />
          <add namespace="System.Web.Mvc.Html" />
          <add namespace="System.Web.Routing" />
        </namespaces>
      </pages>

  </system.web.webPages.razor>

Views typically derive from System.Web.Mvc.WebViewPage which is configured in the web.config. If you are not deploying the DLL with the application, the base class is in the following DLL installed in:

Assembly System.Web.Mvc.dll, v4.0.30319

c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll

Update 1

If you are manually upgrade from MVC X to MVC Y and this requires changing your target .Net Framework (say 4.5 to 4.6) that if you have old references (point to MVC 5 instead of 6) that obviously the older files cannot be used in conjunction with newer files (e.g. MVC 5 DLLs can’t be used against System.Web in 4.6).

Leave a Comment