Setting a Master Page Programmatically in Asp.Net

Leave a Comment

You can specify master pages programmatically by setting the MasterPageFile property of the Page class.
public class BasePage: Page
{
protected override void OnPreInit(EventArgs e)
{
string masterPage =
File.ReadAllText(
Server.MapPath("~/App_Data/MasterPage.config"));
if (!string.IsNullOrEmpty(masterPage))
{
MasterPageFile = masterPage;
}
base.OnPreInit(e);
}
}

The MasterPage is read from the special .config file, then it’s assigned to the MasterPage (.Code in Text) property of the current Page (.Code in Text) instance.

The code is shown below :
void Page_PreInit(Object sender, EventArgs e)
{
    Page.MasterPageFile = "~/NewMaster.master";
}


0 comments:

Post a Comment