101010
101010

Reputation: 15716

The name 'ViewBag' does not exist in the current context -- When in an "Area"

My problem is very similar to this problem, except mine is in a sub-Area (right click, Create Area)

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

I ran the upgrade tool and it did discover the web.config in the area, but I still get the error. My layout page is very simple:

<!DOCTYPE html>

<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

And my content page looks like this near the top:

@model IEnumerable<ProjectName.Models.OrderViewModel>

@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Admin/_AdminLayoutPage.cshtml";
}

<h2>Index</h2>

Upvotes: 17

Views: 24368

Answers (3)

GentryRiggen
GentryRiggen

Reputation: 858

Check to make sure that the web.config file located in your "Views" directory is located at the ROOT of that directory. I accidentally moved it to "Shared" directory and tore my hair out for a while until I figured this out...

Upvotes: 3

mpora
mpora

Reputation: 1479

You should be aware that when creating an MVC application, you get two Web.Config files. One in the root of the project and one under the Views folder. I had the same issue and for some reason when I was working on my project, I accidentally modified the one under the Views. Cleaning it (the one under the Views folder) fixed that error. Hope it helps.

enter image description here

Upvotes: 19

Tae-Sung Shin
Tae-Sung Shin

Reputation: 20643

I have web.config working in an area. See if your web.config in your View folder of the area has s part like following

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

Upvotes: 11

Related Questions