93

I am trying to use ViewBag in my application, I have all of the recent dlls, the latest version of MVC 3, but yet I am still getting the Error:

"The name 'ViewBag' does not exist in the current context"

I have even uninstalled and then re-installed MVC 3 and yet there is no change.

Also, I do not believe that the dll's are showing up in the GAC.

What might be my problem? Or how to add the dll's to the GAC?

Cœur
  • 37,241
  • 25
  • 195
  • 267
efleming
  • 1,269
  • 2
  • 10
  • 10
  • 1
    Keep in mind, for 5.2.2.0 the web.config should point to 5.2.2.0 but the Views/web.config to 5.1.0.0 for MVC assembly – Bart Calixto Oct 17 '14 at 19:30

16 Answers16

85

I was having the same problem. Turned out I was missing the ./Views/Web.config file, because I created the project from an empty ASP.NET application instead of using an ASP.NET MVC template.

For ASP.NET MVC 5, a vanilla ./Views/Web.config file contains the following:

<?xml version="1.0"?>

<!-- https://stackoverflow.com/a/19899269/178082 -->
<configuration>
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
    </configSections>

    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.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" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>

    <appSettings>
        <add key="webpages:Enabled" value="false" />
    </appSettings>

    <system.web>
        <httpHandlers>
            <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
        </httpHandlers>

        <!--
                Enabling request validation in view pages would cause validation to occur
                after the input has already been processed by the controller. By default
                MVC performs request validation before a controller processes the input.
                To change this behavior apply the ValidateInputAttribute to a
                controller or action.
        -->
        <pages
                validateRequest="false"
                pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
                pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
                userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <controls>
                <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
            </controls>
        </pages>
    </system.web>

    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />

        <handlers>
            <remove name="BlockViewHandler"/>
            <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
    </system.webServer>
</configuration>

Adding a ./Views/Web.config file containing this content fixed this problem for me.

Nick Larsen
  • 18,631
  • 6
  • 67
  • 96
crimbo
  • 10,308
  • 8
  • 51
  • 55
  • 3
    Solution at last. I did not deploy the /Views/Web.config file to the server and that missing file was the cause of the error. – Stack Man Nov 30 '15 at 17:24
  • 2
    came back and used this solution a 2nd time! :) – user230910 Jan 28 '16 at 08:17
  • 2
    After wasting over a day trying to figure it out, this did it for me. Thanks. Only thing I needed to add to the tag in " ./Views/Web.config was; `` – dunwan May 30 '16 at 12:33
  • in my case, for some reason the elements weren't in the root web.config but got added to a web.config under 'Views' when i created a MVC5 layout. I migrated the elements to the root web.config and deleted the 'extra'(??) web.config – JDPeckham Apr 04 '17 at 21:46
  • 2
    Dude, God bless you for this. I was EXTREMELY annoyed by this. – Dragan B. Dec 11 '17 at 17:00
39

You need to add the MVC-specific Razor configuration to your web.config. See here: Razor HtmlHelper Extensions (or other namespaces for views) Not Found

Use the MVC 3 upgrade tool to automatically ensure you have the right config values.

Community
  • 1
  • 1
marcind
  • 52,944
  • 13
  • 125
  • 111
  • Thanks! That link helped! I guess this is all a result of making a site that was on the MVC 3 Beta, and then when you get the latest version, the web configs do not get changed. Thanks! – efleming Feb 10 '11 at 18:15
  • I've updated my post with this as well as a related fix: http://stevesmithblog.com/blog/viewbag-does-not-exist-in-current-context/ – ssmith Feb 10 '11 at 18:18
  • You can use the upgrade tool (see updated answer) to ensure your config is correct. – marcind Feb 10 '11 at 19:54
  • 3
    Just a note: if you have additional view locations, i.e., outside the normal `~/Views` location, copy the `~/Views/Web.config` to that location as well. – Dave Thieben Mar 18 '13 at 16:14
19

Try to Clean and rebuild. It worked in my case.

Ruwan Jayalath
  • 361
  • 5
  • 10
  • Can't believe I wasted my time wondering what was wrong with my code... thanks it worked – Mr_Hmp Dec 11 '14 at 12:43
  • infuriating that this works ... i always forget to do this and waste so much time ... should not be necessary – TCC Mar 06 '15 at 20:12
  • in my case i had to delete the packages folder from the solution and do a clean – Nerdroid Sep 26 '16 at 02:48
9

I had the same problem in a solution that had been upgraded to MVC 5 in Visual Studio 2015.

In the web.config file within the Views folder (not the root web.config), I updated the version number referred to in <configSections> from 2.0.0.0 to 3.0.0.0.

<configuration>
    <configSections>
      <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      </sectionGroup>
  </configSections>
Jon Crowell
  • 21,695
  • 14
  • 89
  • 110
6

After trying different things, it turns out it was VS cache. You can resolve it by deleting the cache files located in:

C:\Users\your.name.here\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache

I closed my project, deleted the files on that path and reopened my project, cleaned the solution and built it again and the problem was solved

The files will be recreated when you next launch Visual Studio

Silver Solver
  • 2,310
  • 1
  • 13
  • 19
  • This worked for me in v15 (VS 2017) as well. I probably never would have thought to do this...thanks for a big time savings, Wilson & Silver! – Paul Schroeder Feb 12 '18 at 16:06
  • Universal path `%LOCALAPPDATA%\Microsoft\VisualStudio\14.0\ComponentModelCache` – fiat Nov 19 '18 at 02:51
3

I had the same problem and crimbo gave me the right clue, it was caused by the ./Views/Web.config file which was present but not containing the right namespaces I guess...

I created a blank MVC5 project and imported its ./Views/Web.config into my existing project and the red waves under every ViewBag use are gone !

JJP
  • 1,439
  • 17
  • 21
  • Visual Studio 2013 , created blank web project with MVC box checked. It creates the all file structure with minimum MVC namespace references. I added a simple controller and view. I got compile errors "The type or namespace name 'Ajax' does not exists in the namespace 'System.Web.Mvc' (are you missing an assembly reference)". File Editor also shows the warning "The name 'ViewBag' does not exist in the current context". Go to Project references, find System.Web.Mvc, set the local copy to true. clean the build and rebuild, it solved my problem. – Kagan Agun Sep 20 '15 at 21:45
2

If you use Visual Studio 2013 and you like use MVC 3, you get this error because Visual Studio 2013 does not support MVC 3 natively (even of you change ./Views/web.config), only MVC 4: https://msdn.microsoft.com/en-us/library/hh266747.aspx

Hernaldo Gonzalez
  • 1,977
  • 1
  • 21
  • 32
2

I had a ./Views/Web.Config file but this error happened after publishing the site. Turns out the build action property on the file was set to None instead of Content. Changing this to Content allowed publishing to work correctly.

Kcoder
  • 3,422
  • 4
  • 37
  • 56
1

I had this problem after changing the Application's Default namespace in the Properties dialog.

The ./Views/Web.Config contained a reference to the old namespace

csharpsql
  • 2,190
  • 1
  • 19
  • 24
  • Yes, and it gives an error message on the completely wrong place.. its worth checking if all the namespaces exist that are referred to in ALL web.config files - I had a old namespace in the Area's web/config file causing lots of issues – user230910 Jan 28 '16 at 08:40
1

In my case, changing the webpage:Version to the proper value resolved my issue, for me the correct value was(2.0.0.0 instead of 3.0.0.0) :

<appSettings>
        <add key="webpages:Version" value="2.0.0.0"/>
        <add key="webpages:Enabled" value="false"/>
Robin Leblond
  • 71
  • 1
  • 9
1

After trying all approaches, none of them worked for me since all I have was correct configurations. finally

Deleting all files from "temp" and "%temp%" from system helped to resolve this issue.

Open Run command(Windows+R) and type above strings and delete all temporary files.

Champ
  • 690
  • 1
  • 7
  • 13
1

If you had tried all available answers and still cannot find the answer this might solve issue. If you have different solutions configurations like Debug, Release etc then set project output path to 'bin' and compile project. Revert change after compiling.

Project Output Path

VS looks for dlls in bin folder

Naga Sailesh
  • 786
  • 1
  • 8
  • 13
1

I had already tried deleting the bin and obj file and restarting VS and had no luck.

I've also had this issue many times and it's a pain to solve each time. Often it is due to the web.config file not having the correct version of one of the references. This means click on the reference in Visual Studio to see the version in the property tab, and then match it to the version in the web.config files.

Another way is (if possible) upgrade to a later version of the .net framework and then deleting bin/obj files and restarting Visual Studio. I can only assume it's changing something in the

A quick check of the diff between the csproj file doesn't actually show any major difference... But the differences it did show was (I've added (remove) to show the old line)

<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> (remove)
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>(remove)
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>

In the Web.Config file (not the one in View)

<add key="webpages:Version" value="2.0.0.0" /> (remove)
<add key="webpages:Version" value="3.0.0.0"/>

It also added (to the same web.config file) but I manually removed it

 <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>

Finally, in the Package Manager Console, add update-package

Run the website locally and see any compilation errors which was fixed by my second paragraph (matching the versions of the references)

Dave
  • 8,163
  • 11
  • 67
  • 103
0

I updated webpages:Version under in ./Views/Web.Config folder but this setting was also present in web.config in root. Update both or remove from root web.config

user1412699
  • 1,846
  • 1
  • 13
  • 15
0

As @Wilson Vallecilla already mentioned. Please do the below steps to delete the cache:

Please follow below path to discover the files:

C:\Users\your.name.here\AppData\Local\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 closed my project, deleted the files on that path and reopened my project, cleaned the solution and built it again and the problem was solved

Deleting your Temporary ASP.NET Files also helps. C:\Users\your.name.here\AppData\Local\Temp\Temporary ASP.NET Files.

This works for me.

Thanks!

Trilok Pathak
  • 2,931
  • 4
  • 28
  • 34
0

For MVC5, in case you are building an application from scratch. You need to add a web.config file to the Views folder and paste the following code in it.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.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" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
</configuration>

Note that for MVC 3 you will have to change version to 3.0.0.0 at

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

You may have to close and open the *.cshtml page again to see the changes.