ASP.NET MVC: Folders with Multiple Views and _ViewStart.cshtml File

I have an MVC project that requires two different View folders. One of them is in ~/Views/ and one in ~/Framework/Views/ . This is done by creating a custom viewing mechanism based on the razor viewing mechanism as follows:

 public class MyViewEngine : RazorViewEngine { private static string[] AdditionalViewLocations = new[]{ "~/Framework/Views/{1}/{0}.cshtml", "~/Framework/Views/{1}/{0}.vbhtml", "~/Framework/Views/Shared/{0}.cshtml", "~/Framework/Views/Shared/{0}.vbhtml" }; public MyViewEngine() { base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(AdditionalViewLocations).ToArray(); base.ViewLocationFormats = base.ViewLocationFormats.Union(AdditionalViewLocations).ToArray(); base.MasterLocationFormats = base.MasterLocationFormats.Union(AdditionalViewLocations).ToArray(); } } 

The problem is that I want to use a different _ViewStart.cshtml file in each of the 2 views (i.e. ~/Views/_ViewStart.cshtml for the views found in the ~/Views/ and ~/Framework/Views/_ViewStart.cshtml folder ~/Framework/Views/_ViewStart.cshtml for views found in ~/Framework/Views/ Folder), however, the View Engine uses only the first one found, which is original in ~/Views/ .

Can this be done?

thanks

+4
source share
2 answers

It is definitely possible, I think you just missed something.

I myself tested this using the viewing mechanism you provided (copied and pasted verbatim). I do not see the same behavior as you. I have two _ViewStart.cshtml , one on ~/Framework/Views/_ViewStart.cshtml and one on ~/Views/_ViewStart.cshtml .

When I run the view in ~/Framework/Views/ , it uses _ViewStart.cshtml in the Framework folder. When I run the view in ~/Views/ , it uses _ViewStart.cshtml in the ~/Views/ folder.

Double-checking the code in RazorViewEngine with DotPeek also confirms that this is exactly how it should behave. The viewer starts checking for a file named _ViewStart.cshtml in the same folder as the rendered view, and then rises to the directory tree until it reaches the root of the application.

+6
source

The selection of _ViewStart is hierarchical, but you added ~/Framework/Views in parallel ~/Views . I don't think Razor is set up to do what you want (i.e., two completely parallel views). If you put the Framework in the main Views folder, your _ViewStart will load correctly.

+2
source

All Articles