Problem:
Newly published a MVC web site, got a error message when trying to visit a page:
Compiler Error Message: CS0103: The name 'ViewBag' does not exist in the current context
Analyze:
The MVC sdk has already been installed on the host machine. By looking into the ViewBag’s definition, found it resides in the System.Web.Mvc.dll. So I copied this dll to the web folder’s ~\bin folder, but the error message is still there. And then I double checked the cshtml file and the error message, it was saying the ‘ViewBag’ does not exist in the current context, so I must lost the relative referencing statements. But adding these referencing statements in all the cshtml files is quite annoying, there must be a central place for adding these statements once and will take effects on all the cshtml files.
Solution:
By double checking the web.config, I found I’ve deleted some nodes that related these referencing statements some days earlier for fixing another issue. So I pasted these lost statements and then revisit the page, and then the error was gone!
If you removed these Razor related settings by purpose not to break some sub-applications, then you can paste these Razor related settings to the web.config under the ~/Views folder.
<?xml version="1.0"?> <configuration> <configSections> <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false"/> <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.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=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <!-- ViewBag is in this namespace! --> <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>