Introduction
Master Pages allows you to display common content in multiple pages. It easier to maintain, extend and modify your web site with master pages. This post post explains about how to use master pages and different methods of modifying the content in a master page from individual content pages.
You can create a master page in visual studio by selecting the web site menu option, Add new item and selecting the master page item.
Notice that it contains <%@Master %> directive and includes two content place holder controls. The content from the content page appears in the content place holders. You can add as many ContentPlaceHolders to a Master Page as you need.
Note: You can not cache a Master Page with the OutputCache directive and themes can not applied to master page.
Unlike earlier versions VS 2008 supports Nested Master Pages in design view.
Important points for note
- URL’s used by ASP.NET controls in master pages are automatically reinterpreted relative to the master page.
example If your application is named MyApp, then you can use the following <img> tag to display an image file located in master page folder.
<img src=â€/MyApp/MasterPages/Sample.gif â€>
You can also use Page.ResolveUrl() method to translate an application relative URL into an absolute URL.
- You can Page.Header.Title and Page.Header.StyleSheet properties to change the title and to apply CSS rules to the Master Page. You can use these properties from the content page.
example Page.Header.Title = “My Home Pageâ€;
Style myStyle = new Style();
myStyle.BackColor = System.Drawing.Color.Red; Page.Header.StyleSheet.CreateStyleRule(myStyle, null, ‘html’);
- Exposing Master Page Properties- You can write properties and methods in Master Page and they can be modified from any content page.
example Master.BodyTitle = “Test titleâ€;
- Finding the control in Master Page- For example Master Page Containing a control named BodyTitle. The content page can use FindControl() method to retrieve the Literal Control from the Master Page.
example
Literal ltlBodyTitle = (Literal)Master.FindControl(“ltlBodyTitleâ€);
- Loading Master Pages Dynamically—You can associate different master pages to content page. You can use Page PreInit event to dynamically load the masterpage
example
Conclusion
This post explained different ways of using master pages and to take the advantages of master pages in your application.
Share this post : |