The name 'ViewBag' does not exist in the current context
Asked Answered
K

16

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?

Kyliekylila answered 10/2, 2011 at 16:56 Comment(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 assemblyEldred
R
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.

Redemptioner answered 10/2, 2011 at 17:19 Comment(4)
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!Kyliekylila
I've updated my post with this as well as a related fix: stevesmithblog.com/blog/…Mozellemozes
You can use the upgrade tool (see updated answer) to ensure your config is correct.Redemptioner
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.Pasco
E
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://mcmap.net/q/56934/-the-name-39-viewbag-39-does-not-exist-in-the-current-context -->
<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.

Etheleneethelin answered 11/11, 2013 at 5:12 Comment(5)
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.Tailgate
came back and used this solution a 2nd time! :)Lethalethal
After wasting over a day trying to figure it out, this did it for me. Thanks. Only thing I needed to add to the <namespaces> tag in " ./Views/Web.config was; <add namespace="System.Web.Optimization"/>Afresh
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.configVioloncello
Dude, God bless you for this. I was EXTREMELY annoyed by this.Spangle
R
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.

Redemptioner answered 10/2, 2011 at 17:19 Comment(4)
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!Kyliekylila
I've updated my post with this as well as a related fix: stevesmithblog.com/blog/…Mozellemozes
You can use the upgrade tool (see updated answer) to ensure your config is correct.Redemptioner
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.Pasco
H
19

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

Hypabyssal answered 18/3, 2013 at 4:6 Comment(3)
Can't believe I wasted my time wondering what was wrong with my code... thanks it workedAnemia
infuriating that this works ... i always forget to do this and waste so much time ... should not be necessaryGamekeeper
in my case i had to delete the packages folder from the solution and do a cleanSarong
C
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>
Cinderellacindi answered 31/8, 2015 at 14:56 Comment(3)
Thank you very much! This version stuff is crazy. Everytime I turn around MS upgrades are all over each other. Ling to SQL is replaced by Entity Framework, MVC has gone from 1 to 6, on and on.Conard
Thanks, fixed my issue with VS2017.Ailbert
Fixed VS 2019 mvc 5 app.Longevous
L
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

Lenient answered 11/2, 2016 at 8:59 Comment(2)
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!Cultured
Universal path %LOCALAPPDATA%\Microsoft\VisualStudio\14.0\ComponentModelCacheGraeme
P
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 !

Pepita answered 18/12, 2013 at 8:59 Comment(1)
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.Keynote
K
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

Kino answered 26/1, 2015 at 17:38 Comment(0)
D
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.

Degree answered 24/2, 2015 at 20:5 Comment(0)
O
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

Offense answered 11/12, 2015 at 10:9 Comment(1)
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 issuesLethalethal
L
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"/>
Letterpress answered 21/3, 2016 at 20:31 Comment(0)
B
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.

Baiel answered 19/7, 2016 at 18:47 Comment(1)
Thank you! After trying everything, this worked for me.Bridoon
C
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

Cliftonclim answered 27/10, 2016 at 8:44 Comment(0)
E
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)

Epictetus answered 8/11, 2017 at 7:44 Comment(0)
S
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

Spaulding answered 6/9, 2016 at 10:0 Comment(0)
J
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!

Jinajingle answered 12/2, 2019 at 10:41 Comment(0)
M
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.

Mitchmitchael answered 5/9, 2019 at 11:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.