Sunday, April 23, 2006

Problem with Master Pages in ASP.Net 2.0

I have come accross a major problem in master pages in the new asp.net 2.0. Here is a section of my code.

Dim myMaster As MasterPage = Page.Master
Dim myControl As Control = myMaster.FindControl("ReportMenu")

Dim myControlType As Type = myControl.GetType
Dim mtype As Type = myControl.GetType
Dim minfo As MethodInfo = mtype.GetMethod("Populate")
Dim myparamarray() As Object = {myArray}
minfo.Invoke(myControl, myparamarray)


This code simply locates a control in my web page. This page happens to belong to a master page, so while searching for the control it has to move down through the structure - Master - Page - Control. When the control 'ReportMenu' is located, it uses reflection to invoke the Populate method in that control. Working in the VS 2005 environment this all works fine. However moving over to a pre-deployment server this error occurs.


Unable to cast object of type 'ASP.masterreporting_master' to type 'MasterPage'.

The culprit line is.

Dim myMaster As MasterPage = Page.Master


After a quick search online I came accross this link.

http://visualbasic.ittoolbox.com/blogs/featuredentry.asp?i=7878

The web.config file has an element

<compilation debug="true" strict="false" explicit="true">

By default, batch compilation is set to true, so add the attribute batch="false" to this element. There is apparently a fix for this issue according to Scott Guthrie in the post mentioned above.