ChatGPT解决这个技术问题 Extra ChatGPT

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

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?

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

N
Nick Larsen

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.


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.
came back and used this solution a 2nd time! :)
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"/>
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
Dude, God bless you for this. I was EXTREMELY annoyed by this.
C
Community

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.


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!
I've updated my post with this as well as a related fix: stevesmithblog.com/blog/…
You can use the upgrade tool (see updated answer) to ensure your config is correct.
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.
R
Ruwan Jayalath

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


Can't believe I wasted my time wondering what was wrong with my code... thanks it worked
infuriating that this works ... i always forget to do this and waste so much time ... should not be necessary
in my case i had to delete the packages folder from the solution and do a clean
J
Jon Crowell

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>

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.
Thanks, fixed my issue with VS2017.
Fixed VS 2019 mvc 5 app.
S
Silver Solver

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


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!
Universal path %LOCALAPPDATA%\Microsoft\VisualStudio\14.0\ComponentModelCache
J
JJP

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 !


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.
H
Hernaldo Gonzalez

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


K
Kcoder

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.


c
csharpsql

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


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
R
Robin Leblond

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"/>

C
Champ

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.


Thank you! After trying everything, this worked for me.
N
Naga Sailesh

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.

https://i.stack.imgur.com/4gRrz.jpg

VS looks for dlls in bin folder


D
Dave

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)


u
user1412699

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


T
Trilok Pathak

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!


A
Ashish Kaul

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.