Wednesday, October 15, 2008

A problem when setting the page title dynamically in ASP.NET

Today I encountered a weird problem with ASP.NET. What I wanted to do was really simple. I wanted to change the page title dynamically in code, that's all. In my scenario I had a page that inherits from a basepage class. In that base page class I append the site name to the page title, e.g. if the page title is 'page title' (without the quotes) and the site name is 'mysite.com', I add the site name to the page title so that it becomes 'page title - mysite.com'

In my page, I overrode OnLoad and set the page title in there, but for an unknown reason I always got an empty string for the page title in the basepage class. So, I created a test page, overrode OnLoad() and set the page title in there, surprisingly that worked. I couldn't see any difference between the two pages, I commented all my code and still got a blank title in the basepage class. Finally, I noticed that the only difference between the two pages is that in my page, the title is set to an empty string in the page directive (ie. Title=""). While in the test page, the title is set to the default value (which is "Untitled Page"). By not keeping the title set to an empty string (just put anything in there) it finally worked.

This seems like a bug, I doubt this behavior is by design. Anyway, to sum up. If you want to set the page title dynamically in your code, make sure you have a "non empty string" for the page title, i.e., if you have Title="" in your page directive, replace it with any other value, e.g. Title="some value" (even though you're going to change this value), otherwise, it will not work.