Runtime Master Pages

January 23rd, 2009

Master pages are great time savers in ASP.NET and we use them extensively to simplify user interface management in our applications. Recently, I ran into a situation where the master page to be used needed to be set from the Database. Turns out this is relatively simple to do if you know the path to the master page. You need to harness the Page_PreInit event that fires before the Page_Load and set the master page at runtime:

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

The other problem I ran into was accessing a control on the master page from the web form that uses the master as a template. This is important because if all the inter-changeable master pages have the same control names they become useable from the web form irrespective of their location on the page. One way is to define the same content areas in all the master pages and set them accordingly within the child, however in many cases you’d be duplicating the code relating to the control on the web forms. The other option is to use the FindControl function on the Master object. In order for this to work it needs to be cast to the appropriate control class. In the case of a Literal the syntax works out like this:

((Literal)this.Master.FindControl("literalControl")).Text = "Foobar";

Nice and easy.

Validators rock the house

May 29th, 2004

Finally got these suckers working. You do need to define the control that needs to be validated before hand. After that it works like a charm. Probably the biggest time saving feature I’ve seen in .Net so far.

Goddamn ASP.Net Custom Validators

May 29th, 2004

Been messing about with ASP.Net and was having trouble getting CustomValidators to work correctly. I wanted Server Side validation for a Username (check to make sure that the username does not exist). I got it to the point where it comes back if an error occurs without writing to the database but it didn’t display the error. Found this page: 4 Guys from Rolla that provided an easy server side only example. Still didn’t fix why my message wasn’t being displayed though. I think it has something to do with setting the controls to validate at design time in the design window. I am currently setting those properties at runtime through a function. Lets see how it goes when I switch that.