A ViewStartPage can be used only with with a page

2019-05-16 23:43发布

问题:

Due to some necessities I created my own custom View Start as follows:

public abstract class MyViewStart : System.Web.Mvc.ViewStartPage {
    public My.Helpers.ThemeHelper Themes { get; private set; }

    public MyViewStart() : base() {
        Themes = new Helpers.ThemeHelper(base.ViewContext)
    }
}

The need is that in the _ViewStart I need to do some layout file finding that depends on the theme, what it does is irrelevant to the problem.

My Views/Shared/_ViewStart.cshtml looks like this (irrelevant stuff removed):

@inherits MyNamespace.MyViewStart
@{
    Layout = Themes.ThemeLayout;
}

So, we have a custom ViewStart class that derives from the standard ViewStartPage. The standard _ViewStart.cshtml is a ViewStartPage. The new _ViewStart.cshtml is a MyViewStart page which in turn is a standard ViewStartPage so all is covered in the inheritance.

However, when I run the application I get the error:

A ViewStartPage can be used only with with a page that derives from WebViewPage or another ViewStartPage

which is thrown by the "Themes = new Helpers.ThemeHelper" line in the constructor of my custom view start class. So, why does it throws that exception when my custom view start class IS a child of ViewStartPage ???

回答1:

You cannot access the ViewContext in the constructor, but if you override ExecutePageHierarchy you can do it there. I modified your code like this to make it work:

public abstract class MyViewStart : System.Web.Mvc.ViewStartPage {
    public My.Helpers.ThemeHelper Themes { get; private set; }

    public override void ExecutePageHierarchy()
    {
        this.Themes = new Helpers.ThemeHelper(this.ViewContext);
        base.ExecutePageHierarchy();
    }
}