I'm trying to have all my views inherit from a custom class so that I can add certain behaviour and values to all pages, but I'm having some issues. I tried subclassing System.Web.Mvc.WebViewPage but I'm forced to implement an Execute procedure that I don't know what it should do. Also, if I try to access the Context variable, I get a null reference (really weird). This leads me to think that I may have the wrong base class....
Any thoughts?
Diego,
System.Web.Mvc.WebViewPage
is the right base type (and you should have another class inheriting fromSystem.Web.Mvc.WebViewPage<TModel>
if you want strongly-typed views). You should mark your own class asabstract
so that you are not forced to implement the Execute method.Update: To configure all your views to use your custom base class, look into the
~\Views\Web.config
file. Inside of it there's a Razor-specific section where you can use thepageBaseType
attribute to configure your custom type.As far as the Context property is concerned, it should be fully initialized once the view is executing. However, it might not be available if you try to access it too early (for example, from your classes constructor). When are you trying to access it?
The Execute method is something that is provided by the Razor compiler when your view is compiled. For example, given the following view file
The Razor compiler will behind the scenes generate the following class (this is a simplification, so the details might be off, but it should convey the point)
Then the framework calls the Execute method on your view class and your view gets executed.