Setting the masterpage in Page_PreInit for ASP.NET MVC?
In a regular ASP.NET application, I have an httpModule where I handle the PreRequestHandlerExecute event and hook into the page's PreInit event so I can programatically set the masterpage. However, when the application is ASP.NET MVC, my httpModule no longer does what it's suppose to do because the CurrentHandler inside PreRequestHandlerExecute is of type System.Web.Mvc.MvcHandler rather than System.Web.UI.Page, so it's not so obvious to hook into the page's PreInit event.
My question: how do I mod开发者_如何学Pythonify my httpModule to programatically set the masterpage for an ASP.NET MVC view page? Is this even possible with an MvcHandler in the PreRequestHandlerExecute event?
This blog posting was quite helpful.
http://codeofrob.com/archive/2009/11/01/dynamically-switching-between-master-pages-in-asp.net-mvc.aspx
In the controller I determine the master page needed (facebook app, mobile etc) then set the master page in there rather than in the page itself. Seems cleaner, though Matt's answer works also.
Simply add this to your aspx view.
<script runat="server">
protected void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "Custom.Master";
}
</script>
精彩评论