ASP.NET Master Pages Tips and Tricks

Really nice article by Dan Wahlin in which he writes about ASP.NET Master Pages Tips and Tricks. Here is part of it:

With the release of ASP.NET 2.0, developers were given a simple and effective way to apply a consistent layout across multiple pages in a website. By creating a file with a .master extension that defined a website’s overall layout template and referencing it with the Page directive’s MasterPageFile attribute, website development and maintenance took a step forward in the direction of greater productivity.

Master pages have been around for over one and a half years, so I won’t cover the fundamentals of creating and using them, as many tutorials and books have already been written about the topic. Instead, I’ll focus on a few tips and tricks that can be applied when using master pages. To start, let’s examine how the MasterType directive can be used to reference master page controls in a strongly-typed manner from a content page.

Using the MasterType Directive

Pages that reference controls in a master page, such as a Label in the header, or Menu on the left or right of a website template, typically do so by using the Page class’s Master property along with the FindControl() method, as shown in Figure 1.

Figure 1: controls in a master page can be accessed by using the Master property combined with the FindControl() method.

While this approach certainly works, any misspellings in the quotes will not be caught by the compiler, resulting in a runtime error or a null object reference being returned. Fortunately, a strongly-typed solution is available that doesn’t involve casting the Master property to the base class of the master page in order to access its members (keep in mind that any server controls defined in the master page won’t be accessible even after a cast is performed, because they’re marked as protected by default).

read original


Leave a Reply

Your email address will not be published. Required fields are marked *