Why can Razor not see ViewBag, Url.Content, etc. when the layout page is outside ~/Views/Shared?

StackOverflow https://stackoverflow.com/questions/6023583

  •  14-11-2019
  •  | 
  •  

Question

I'm working on a CSS framework that I can drop in to other projects as a NuGet package.

To keep things clean, the entire framework - views, styles, images, and master pages / layout pages - is actually stored under ~/CssThing/

Works perfectly with the WebForms view engine, but when I move the _layout.cshtml file into ~/CssThing/ and then modify my Razor page to say:

@{
Layout = "~/CssThing/_layout.cshtml";
}

it starts complaining that ViewBag is not defined, or that The name 'Url' does not exist in the current context, or various other bits of weirdness that suggest the view is no longer inheriting from the proper base class.

How can I get this to work?

NOTE: The reason everything's split out like this is there's no way to force NuGet to overwrite existing code, and there's no way to spin up an empty MVC3 web application without picking up all the jQuery, etc. references, so rather than risk my framework getting half-deployed because half the files were already present, I'm keeping everything completely seperate.

Was it helpful?

Solution

Check you have a web.config in the new views directory. It's best to copy the one created by the default project in Views. This web.config defines Razor's settings like default page base class and what namespaces are implicitly available. Those namespaces define what HTML helpers you can use.

OTHER TIPS

You need to manually specify @inherits WebViewPage, or add the default Web.config section (which sets the base type) to the folder with the views.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top