开发者

Set Masterpage from Global.asax in ASP.NET

I want to set the Masterpage property in Global.asax.

This is wha开发者_如何学Got I have done but I get a NullReferenceException on the first line. Any ideas how to do this?

protected void Application_PreSendRequestContent(Object sender, EventArgs e)
{
    System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;               

    if (Session["lang"] == "eng")
    {
        page.MasterPageFile = "SideMasterPageEng.master";
    }
}


Application_PreSendRequestContent is way too late in the page lifecycle to be doing this. The MasterPage has already been executed at this stage.

Global.asax is really a place for Application events rather than page specific. Be aware that many of the application events like Application_BeginRequest are called on any request, not just aspx Page requests. Many of these events are fired for every js script, image, css file etc that is requested.

Here is a good list of the events in Global.asax: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5771721.html

The only place that I know that you can definately change the master page is in the page Page_PreInitevent handler

protected void Page_PreInit(object sender, EventArgs e) 
{ 
    this.Page.MasterPageFile = "~/Custom.master";
}

Edit: Reading your comments, it sounds to me that you need to derive your pages from a base page which makes the change in one place.

using System;
namespace TestWebApplication
{
    public class PageBase : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
           Page.MasterPageFile = "~/Custom.master";
        }
    }
}

Then alter all of your pages to inherit this instead of System.Web.UI.Page...

//public partial class WebForm1 : System.Web.UI.Page 
public partial class WebForm1 : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜