Tuesday, January 22, 2008

Change Master Page styles based upon the current page

In ASP.NET, a common practice is to create a master page, and expose content regions to the .aspx pages to hold page-specific content. One way that you can dynamically change the Masterpage content (i.e. add/remove asp controls, change style values) is to determine the actual page name (xyz.aspx) that is going to be displayed.
string filePath = Context.Request.FilePath;
string pageName = filePath.Substring(filePath.LastIndexOf('/') + 1);
//pageName will now hold the name of the file requested


Once we figure out which page is being requested, we can handle the behavior.

For example, if the page "NoBorderTables.aspx" should set all the tables to have no border, you can execute some code like this:
 protected void Page_Load(object sender, EventArgs e)
        {
            
            if(!IsPostBack)
            {
                string filePath = Context.Request.FilePath;
                string pageName = filePath.Substring(filePath.LastIndexOf('/') + 1);
                
                switch(pageName.ToLower())
                {
                    case "NoBorderTables.aspx":
                         foreach (Table t in this.Page.Controls)
                         {
                           t.BorderStyle = BorderStyle.None;
                         }
                         break;
                 )
             )
         }
                    

No comments: