Search code examples
asp.net-2.0code-behindweb-deployment-project

How to reference the same CodeBehind class from multiple .aspx files (and be able to pre-compile the website)?


I have a set of aspx pages that each live in their own directory and reference a single aspx.cs code behind file.

This has worked fine previously because I never tried to pre-compile the site. IIS must have individually compiled each aspx, linking them to the contents of App_Code but never referencing more than one aspx at a time.

Now that I'm trying to pre-compile the website using Web Deployment Projects I keep getting errors about the same class being found in multiple assemblies.

I can't just drop the aspx.cs in App_Code and subclass it because it wouldn't be able to find the controls on the .aspx pages when compiling. Maybe I could explicitly define every control on the page in the .cs? But would that allow them to be wired up correctly?

Any other ideas on how I can reference the same Page class from multiple .aspx pages and be able to pre-compile the entire website?

Edit: It looks like CodeFileBaseClass may be what I want. I'll drop my .cs in App_Code, explicitly define all my pages controls, then specify this classs as CodeFileBaseClass in the aspx files that inherit from it. Thoughts?

Edit2: I came up with a solution, but since I can't yet mark it as accepted, I'd still like to see if anyone else could come up with some other solutions for this problem.


Solution

  • The solution was to:

    1. Take my .aspx.cs and copy it into App_Code with a new class name (FooPage)
    2. Modify FooPage to explicitly declare all server side controls it references.
    3. Now for each of my .aspx files that referenced the original .aspx.cs:
      1. Create an .aspx.cs file for them.
      2. The class in the .aspx.cs will inherit from the class I moved into App_Code
      3. Set CodeFileBaseClass="Namespace.To.FooPage" in the .aspx

    This allows ASP.net to easily wire up all the server side controls in the .aspx to the protected members of the base class.

    Now I only have 1 of each class in my code and can pre-compile the entire site!