czetsuya
czetsuya

Reputation: 5053

_ViewStart stops working after creating a razor custom view engine

I've created a razor custom view engine that extends RazorViewEngine. Then suddenly I'm unable to access the variables I've defined in _ViewStart.cshtml at the /Views folder, which normally work on a default project initialized by VS2010 MVC3 template.

My question is how to enable _ViewStart in a razor custom view engine?

Upvotes: 4

Views: 471

Answers (1)

Nathan Anderson
Nathan Anderson

Reputation: 6878

Without seeing your code I can't specifically say what's going wrong, but after viewing the source the for the RazorViewEngine I think may have an idea what you are not doing.

This is what the CreateView method looks like:

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var view = new RazorView(controllerContext, viewPath,
                                 layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)
        {
            DisplayModeProvider = DisplayModeProvider
        };
        return view;
    }

You can see they are passing a value of true in for the runViewStartPages argument on the RazorView constructor. Looking at the source of the RenderView method in the RazorView class reveals that this boolean parameter is used to create a StartPageLookupDelegate that is responsible for finding the _ViewStart file and compile it into the execution hierarchy.

WebPageRenderingBase startPage = null;
if (RunViewStartPages)
{
    startPage = StartPageLookup(webViewPage, RazorViewEngine.ViewStartFileName, ViewStartFileExtensions);
}
webViewPage.ExecutePageHierarchy(new WebPageContext(context: viewContext.HttpContext, page: null, model: null), writer, startPage);

So this means you are likely doing one of two things:

  1. Overriding the CreateView method of the RazorViewEngine and not initializing a RazorView in the manner listed above.
  2. Overriding the RenderView method of the RazorView without creating a StartPageLookupDelegate and passing it into the ExecutePageHierarchy method.

Hopefully this helps send you down the correct path to finding a solution!

Upvotes: 1

Related Questions