I recently ran into a very strange problem with ASP.Net 2.0. I have used master pages for a couple of years now, and this is the first time I encountered such an odd problem.
Well, I have a label (Label1) on my master page (say MasterPage.master), this label can be accessed by the content pages via a simple property, for example:
And in my content page, I wanted to set a value to TestText via:
It is just as simple as that. Over the years I have used this exact approach to update shared properties across many different pages (e.g. page tile on the master page). But the code I was writing at work threw a runtime exception (InvalidCastException), complaining that it couldn’t cast my page (say Default.aspx) back to the master page (MasterPage). The actual page logic was quite complex, but the problem at hand was nevertheless exactly the same as the code illustrated above.
At first I thought that I might have over looked something, but carefully looking through code (as you can imagine, the code to achieve this is very trivial) multiple times, I was convinced that there’s something wrong with the .Net Framework.
Out of curiosity I also tried the <%@ MasterType directive. But using either TypeName or VirtualPath resulted the same exact problem. When using VirtualPath, I could see the error at design time and using TypeName the error appeared at runtime.
After scratching my head for quite sometime, I decided to look through Microsoft’s Knowledge base articles. And sure enough, here is the article that describes the exact same problem I faced. Unfortunately, the suggested patch did not solve my problem and since this knowledge base article was updated only a few days ago (12/3/2007) it was not all that surprising that the patch did not work for my particular case.
I guess I will have to wait for the SP2 release of .Net framework 2.0 to get this simple code to work… In the mean time, I had to move the Label control to each individual content page (obviously not an elegant solution).