Search code examples
c#html.netcode-behind

Pass objects/vars between Page_PreInit and Page_Load


I am building pages dynamically using a database to store the page info and .NET (C#) to build pages. Part of that process is to set the masterpage (in the code-behind) based on what is in the database and, as I understand it, that has to be done in Page_PreInit.

My problem is how to pass objects and variables from Page_PreInit to Page_Load.

I have been able to make it work as follows, but am having random compiling errors when using this method:

public partial class BuildPage : System.Web.UI.Page
{
    protected static string pageData;

    protected void Page_PreInit(object sender, EventArgs e)
    {
        --- SET pageData = DATA FROM DATABASE, AND SET MASTERPAGE ---
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        --- USE pageData TO BUILD AND DISPLAY THE REST OF THE PAGE ---
    }
}

For various reasons, I'm am not using Visual Studio to compile the page, just letting .NET compile on the fly at the first page request. I have gotten two error messages:

1) "CS0102: The type 'BuildPage' already contains a definition for 'pageData'"

2) "ASPNET: Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl)."

The strange thing is that sometimes the page compiles on the first web request. And, for those times that it doesn't on the first request, after a random number of page refreshes, it will compile perfectly. After it compiles everything appears to work fine until I make another change to the code behind and it has to recompile.

I seem to only get those compiling errors when using that method to share variables between Page_PreInit and Page_Load. In other words, if I simply request the data twice from the database, once in 'Page_PreInit' and once in 'Page_Load' I never get those errors. But I really would rather not double the database load.

So my question really has two parts, first, is that an acceptable way to share variables or is there a better way to pass data from Page_PreInit to Page_Load?

And second, if that is an acceptable way, are the errors unrelated and has anyone seen similar errors that simply go away after repeated web requests before?

Thanks for any and all help! fodder


Solution

  • Using a protected (or private) member is definitely the correct way to share objects between methods in a class. However, your member should not be static. Static means there is a single instance across multiple threads. Every copy of the page which is being executed for the different requests accessing that page are competing to read/write that member.

    Also, your class is marked "partial". That means there could be another class fragment in another file which has additional members and methods for the same BuildPage class. If you declare the same pageData member in both, they will conflict.