一个ViewStartPage只能与从WebViewPage或另一ViewStartPage派生的页使用 [英] A ViewStartPage can be used only with with a page that derives from WebViewPage or another ViewStartPage
问题描述
由于一些生活必需品我创建自己的自定义视图开始,如下所示:
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)
}
}
我们需要的是,在_ViewStart我需要做一些布局文件的发现依赖
的主题,它的作用是不相关的问题。
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.
我的视图/共享/ _ViewStart.cshtml看起来像这样(东西无关删除):
My Views/Shared/_ViewStart.cshtml looks like this (irrelevant stuff removed):
@inherits MyNamespace.MyViewStart
@{
Layout = Themes.ThemeLayout;
}
因此,我们有从标准ViewStartPage派生的自定义ViewStart类。该标准_ViewStart.cshtml是ViewStartPage。新_ViewStart.cshtml是MyViewStart页这又是一个标准的ViewStartPage因此所有覆盖在继承。
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:
一个ViewStartPage只能用从WebViewPage或其他ViewStartPage派生的页面中使用
A ViewStartPage can be used only with with a page that derives from WebViewPage or another ViewStartPage
这是由主题=新Helpers.ThemeHelper我的自定义视图启动类的构造函数抛出线。那么,为什么它抛出异常时,我的自定义视图启动类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 ???
推荐答案
您无法访问ViewContext在构造函数中,但如果你重写ExecutePageHierarchy你可以做它。我修改了code这样的,使其工作:
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();
}
}
这篇关于一个ViewStartPage只能与从WebViewPage或另一ViewStartPage派生的页使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!