Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

Understanding Page Inheritance in ASP.NET 2.0


:P
On this page:

In ASP.NET 1.x the primary code model is based on CodeBehind, which uses inheritance and code generation to manage the code that you as the developer work with. In V1 you create a base class into which the VS.NET Editor generates control definitions from the HTML markup – each control gets an instance field on the form and any explicit event hookups are stuck into the InitalizeComponent section of the page. The ASP.NET engine then generates a class from the HTML markup and inherit from your CodeBehind form, in effect providing the functionality you implemented in that class in addition to the generated code.

Some problems with the 1.1 model

The concept’s pretty straight forward, but in VS.NET 2003 there are lots of problems with this approach that had to do with the code generation into the CodeBehind class. In many cases control declarations would not make it, or event declarations would get lost. Who’s ever lost their datagrid events after saving a page or copying a couple of controls around on it? Worse, if you removed a control from a page VS.NET wouldn’t clean up after itself and leave the declaration and event hook up code in the CodeBehind class. It’s even worse if you were using a plain text editor to manage this on your own, as you’d have to remember to match control definitions in the markup to control definitions and event hookups in the class, so you always have to maintain code in two places.

How ASP.NET 2.0 addresses these issues

In ASP.NET 2.0, the CodeBeside model addresses this issue with Partial Classes. The core model is still the same and based on inheritance, but the rather than using a single class definition ASP.NET 2.0 breaks up the class into two partial classes that get combined at compile time. There’s the class that you write your code into – Page_Load() and any event implementations as well as any field definitions. And then there’s a generated class that contains all the Control definitions and event hookups. When the page is compiled both partial classes are combined and that class is then used as the base that is inherited by the Page parser generated class.

 

The advantage of this approach is that there’s only one place that code generation occurs and it’s at page compile time. So even if you use a plain text editor to create your CodeBeside page it will automatically pick up your control definitions. No longer does VS.NET have to parse the document at design time (well it still does to provide Intellisense support) to create control definitions to inject into your source document. This is of course much more reliable and consistent and makes for much cleaner code. You only see the code you actually wrote yourself.

 

Another advantage of the new page model is the fact that individual pages can (but don’t have to) compile into individual classes. ASP.NET 2.0 can compile pages individually or at the directory level. When you run ASP.NET in debug mode it uses single page compilation. Single page compilation is an awesome feature for debugging pages inside of VS.NET 2005. Because pages can individually compile when they are run you can now execute a page, make a change and immediately re-run the page without explicitly recompiling your project. This is much faster than the 1.1 change and compile steps you had to go through especially on larger projects.

 

This works even if you are running in Debug mode; so you can step through code, find a problem, fix it in the editor and simply re-run the page. This is similar to the way single source debugging worked in ASP.NET 1.x but it now can also work with the more sophisticated and more realistic CodeBeside approach. As you might expect this is a huge timesaver, especially for large projects as you’re saving a long compile step, although the page recompilation is not super fast at least in Beta 2.

How it works

ASP.NET 2.0 makes use of partial classes to provide this improved stability in the page model. The core model hasn’t change all that much from ASP.NET 1.1 as the combined classes are still very similar to the single codebehind page used in 1.1. You still have page inheritance where the ASPX page inherits from your partial class and the generated control definitions.

 

At the CodeBeside level there are two partial classes: There’s the class that you write your code into – Page_Load() and any event methods as well as any field and property definitions and events that you want to define. This page is the ‘master’ partial class as it provides the inheritance structure where you can tell it what to inherit from. Typically it looks like this:

 

namespace Westwind.WebStore

{

      public partial class UploadItemPicture : System.Web.UI.Page

      {

    protected void Page_Load(object sender, EventArgs e)

    {

… implementation here

    }

    protected void btnGo_Click(object sender, EventArgs e)

    {

      … implementation here

    }

      }

}

 

Note that a partial class does not contain control definitions or InitializeComponent that usually hooks up the events. ASP.NET generates the surrogate partial class at compile time that represents the ASPX page code ASP.NET generates another partial class that contains all the control definitions, the event delegate hookups and setting of Page settings (like EnableSessionState, Trace etc.).  Both of these partial classes combine to make up the base class that the ASPX page inherits.

 

This base page is inherited by the class that the ASP.NET page parser creates. The Page parser runs through all of the ASPX script code and creates a class from it that is made up of literal HTML content, expressions that are written straight out into the HtmlTextWriter object, and the Control tree that is parsed and then rendered.

 

You can see this to a large degree if you throw the generated, compiled assembly into .NET Reflector. In case you don’t know about Reflector, run and don’t walk to get it – it’s an awesome tool to figure out how code works, be it your own, Microsoft’s or cough, cough any third parties that isn’t obfuscating their code.


ASP.NET generates assemblies from your classes using the ASP.NET compiler (ASPNET_COMPILER.EXE). You can pre-compile your project and look at the generated assemblies. For more info click here. What you’ll find is something that looks like the Figure below which shows a composite assembly created from the precompiler with the following command line:

 

"<frameworkPath>\aspnet_compiler.exe" -f -v "/wwstore" "d:\temp\deploy\wwstore"

 

I used a virtual IIS path (-v /wwstore) and compiled it into a fixed directory that is to overwritten (-f). This option create one assembly per directory of the Web application which combines all of the pages of the directory into one assembly all starting APP_WEB as the name prefix. The assemblies are randomly named, so finding the right one is not easy if you have more than one directory – usually you can guess by looking at the file sizes.

 

Once you find the right assembly in Reflector it might look something like the figure below. In my case I’ll look at the UploadItemPicture page in the Web. Notice the two classes related to this in the ASP namespace and the Westwind.WebStore namespace:

 

 

The class on the bottom (UploadItemPicture) is my user class, which is the merged version of my partial class, plus the generated page control code and event hookup code. If you look at the properties and methods of this class you will find all the control definitions, which although they weren’t defined in your source code are now there. All of that comes from the generated partial class. The combined class looks pretty similar to an ASP.NET 1.x single CodeBehind class…

 

If you look closely at the figure above you can see that admin_uploaditempicture_aspx inherits from my UploadItemPicture class. The inherited class contains the actual page construction logic for instantiating each of the controls (__Build<ControlName>) and then renders the page using __BuildControlTree(). BuildControlTree is the top level routine that fires of the page rendering process. It renders the form literals, and then renders each of the controls inside of the page. It does this using the containership hierarchy so in this case there’s RenderForm1 which in turn renders each of the child controls. Depending on where controls appear in your page this may look differently. In my example above all other controls are inside of the Form tag, so the other controls are rendered as part of internal code of the Form object.  Each control (except the form tag which requires special handling) is rendered using RenderControl() for each of the control in the Controls Collection and each control manages its own rendering process.

 

BTW, if you quickly want to see the generated page source for the Partial class that has the above definitions in it – you can put an error into your script page in an expression. For example:

 

<b>itemimages/<%= this.ImageFileName_INVALID %><br>

 

On the resulting error page, click on the Show Complete Compilation Source and you should see the code displayed. You’ll want to trigger an error in the ASPX page to make this work, not in the CodeBeside code, because that shows you just the compilation code of your code behind partial class. It’s too bad we can’t see the combined class or at least both classes that make up the composite.

What to watch out for

So far this all sounds really nice – ASP.NET 2.0 provides a solution to the nasty control mismatch problems that so often would creep up in V1 without really giving up any features. Well, mostly, but there are  a few issues you need to be careful of.

 

Most importantly you have to realize that part of your class is dynamically generated at compile time. What this means is that some things are not necessarily available to your code.

 

Let’s presume for a second I wanted to subclass an existing page and use it for a custom class like this:

 

public partial class UploadItemPictureEx : Westwind.WebStore.UploadItemPicture

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

}

 

First off you’ll notice that VS.NET doesn’t show UploadItemPicture as an identified class (it’s black – it should be Teal colored text for a type name).  If you try to run this page it fails too. ASP.NET complains that it can’t find Westwind.WebStore.UploadItemPicture. This even though it exists in the same assembly! You can’t reference other Page classes in your code like this. This is true whether the code is in the same assembly or not. If the UploadItemPicture.aspx page were in a different directory it would end up in a completely different assembly and not visible at all to the current assembly because it doesn’t receive a reference to any of the other directories.

 

This is a pretty major change in the way ASP.NET works. There’s a workaround for this, but it’s not pretty:

 

  • Create a base class for your page and make it inherit from Page
  • Store this Page either in APP_CODE or in a separate assembly so it’s visible to your pages
  • Implement your Public interface on this base Page
  • Then create your Page and make it inherit from this base Page
  • Now when you need to cast, cast to the base type

 

Yes, this is pretty ugly, but it works and it’s not too bad of a workaround once you know what to do. I doesn’t change the way you work much but it requires one additional class and remembering to expose the base methods and properties you want to access at the base class level. You still implement all your code at the UserControl level – the base class is merely there to give you the strongly typed base interface that you can use for Intellisense and getting the proper typecasting to access the interface without Reflection.

User Controls

You have similar issues with controls, but the rules are a little more lenient because apparently Microsoft realized that it’s pretty vital that you can reference user controls from your code. If the control lives in the same directory (ie. it gets compiled into the same assembly) as your current page the user control class will always be visible and you can create and simply cast to it. So the following works just fine:

 

Control ctl = this.LoadControl("MyUserControll.ascx");

this.AddParsedSubObject(ctl);

 

MyUserControll CastCtl = (MyUserControll) ctl;

CastCtl.CustomProperty = "Hell on wheels is no big deal...";

 

 

If the control lives in a different directory (ie. it gets compiled into a separate assembly) you need to make sure that the page that you are loadign the control onto has a <%@ Register %> tag in place on the page, which provide the needed assembly reference. If you DON’T have a the Register tag on the page the following will fail with an error that MyUserControll cannot be found:

 

Control ctl = this.LoadControl("../MyUserControll.ascx");

this.AddParsedSubObject(ctl);

 

MyUserControll CastCtl = (MyUserControll) ctl;

CastCtl.CustomProperty = "Helllo Dolly...";

 

Adding the Register tag fixes this problem. The Register tag on the page acts as an assembly import for the user control’s assembly that makes this work. In the same directory this isn’t necessary because the control exists in the current assembly.

 

For normal application usage this is not a big issue as in most applications developers will drop controls onto a Page visually. However, for dynamically loaded user controls things are going to be tricky – I don’t see how you can truly dynamically load a user control any more assuming you can’t add the <@ Register > directive to the page explictly. Maybe there’s some way to do the equivalent of <@ Register > in code? If there is, I couldn’t find it…

 

All of this worked in 1.1 because you had a single assembly and all pages and controls living in that assembly were visible with the namespace you defined. Now ASP.NET takes some liberties with our namespaces and to some degree there’s a loss of control over where our code generates because there may be multiple assemblies involved.

 

If you think this is confusing as heck – I agree with ‘ya. This is going to throw a lot of people for a loop. Luckily this isn’t the most common scenario but I don’t envy the folks who have designed entire architectures around dynamically loaded UserControls… 

Overall Goodness

This last issue is a bit of a bummer and it smells of a design flaw that wasn't addressed early enough in the cycle. There's a lot of discussion around the page compilation and the way the ASP.NET compiler works and this has become a very hot topic primarily because nobody seems to be able to explain exactly how it's supposed to work. <g> While it sounds major, it really is a marginal issue to most developers. Most will never run into this issue.

 

In return you get a lot of new functionality in the page model that makes a lot more productive. The ability to keep on running and debugging your application without a full application restart alone is a huge timesaver. Add to that the cleaner environment that Partial classes bring and it’s hard to think about going back to VS.NET 2003…

 


The Voices of Reason


 

K. Scott Allen
September 12, 2005

# Page Inheritance in ASP.NET 2.0

Rick Strahl has a fantastic post: “Understanding Page Inheritance In ASP.NET 2.0”. Go read the post now....

Joe Brinkman
September 13, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

DotNetNuke is currently working through the very user control problem you mention above. It is a huge problem for us and as a widely used framework for ASP.Net websites, will affect thousands of developers either directly or indirectly as we are forced to change how "modules" are developed.

Anatoly Lubarsky: Weblog
September 16, 2005

# Rick Strahl on Page Inheritance in Asp.Net 2.0


Anatoly Lubarsky: Weblog
September 16, 2005

# Asp.Net 2.0: Rick Strahl on Page Inheritance


Jim Corey
September 28, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

A bit more on user controls:
If I add a public property or method to a user control, it's not immediately available in intellisense to the page (unlike 1.1).

Once compiled, these are available in intellisense, but say I'm in my page code
and right click on "myControl.myMethod()"
and select "Go To Definition".
It puts me into the metadata and just shows me the stub -- not really where I hoped to be.

But maybe this is just my CTP.


Rick Strahl
September 28, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Yes, if a user control lives in the same directory it IS actually accessible because in theory it compiles into the same assembly. It always should work with the <%@ REGISTER %> keyword.

The stub issue is another silly one but it makes sense - MS is showing you the signature of the generated class for which there is no source code.

Lars Bernerberner
October 02, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Searching for a solution for my problem i found your blog entry Rick:
i also tried to access to declare some variables from the type of one of my UserControls just like you wrote.
My problem is, that it seems not to be possible to tell VS to find the Type of my UserControls. I declared them in the same Project and in the same folder like my page but it didn't help.
If I try the same within one of my UserControls instead of a page, VS finds the type of the other UserControl and compiles

Do anybody have an explaination for this issue?
I'm using VS 2005 Beta 2

regards


Shahed Khan
October 04, 2005

# My Old posts in LiveJournal


Charles Bretana
October 05, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Thanks ! This is a great post... It explains the new ASP 2.0 Page inheritance issues very well.

My initial reaction is that I think MS may have made a mistake here... The downsides of this architecture (loss of control, obfuscation, & inability to access page objects without what seem to be real hacks) are, imho, more significant than the minor benefits that the approach provides... And these benefits seem, primarily, to be addressed at the lowest skill level of web developers, those that primarily do things vsually using he designers, and want the maximum amount of stuff done for them. The problems the architecture "eliminates" are generally those that only occur when you are not familiar with the way the various code objects need to be "wired up", and are relying on the "automatic" features of Visual STudio to do that for you.

Charles Bretana
October 05, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

A co-worker says that he has heard that this behavior, although the default, can be modified to work the way it did in 1.1 ...

Has anyone heard of this? or how to do it?

Tim Farley
October 11, 2005

# Doing @Register tags in code

Rick said:
>> Maybe there’s some way to do the equivalent of <@ Register > in code?
>> If there is, I couldn’t find it…

I don't know of a way to do it in code, but I just stumbled across a way to do it in web.config. It's a new sub-element of the <pages> element called <controls>

Read about it here:
http://msdn2.microsoft.com/en-us/library/ms164640(en-US,VS.80).aspx

helli
October 15, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

First of all: thanks for this article. It helped me a lot that I can reference user controls from the code.
I implemented a System.Web.UI.UserControl to a another UserControl. It seemed to work perfectly.
Unfortunatley I encountered one strange error: The UserControl that I added contained a Gridview with paging enabled. The paging worked fine unless I try to change from a page index > 0 to the first page (pageIndex = 0). In that case the PageIndexChanging event is not fired. The same applied if I tried to go from the last page to a previous page.

The paging works perfectly if I integrate the same code in a page.

After 4 hours of testing, I gave up and am now work with a workaround.

energed
October 16, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

If dynamic loading of user controls is not supported like it used to be, is there any preferance how to do it now? Multiple pages with different controls?

Ps. Sorry about this. Could be really stupid question.

Scott Olson
October 19, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Thanks for the informative article - good examples. I do have one question that does not seem to be addressed here:

I am attempting to dynamically load one of a fixed set of user controls from within a user control. In this case I can register them, but I am still not seeing access to the others' public properties in the code. They even reside in the same directory! Any ideas?

Andrew
October 20, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

I've come across a funny problem with UserControls that seems related to the departure from a single assembly.

I'm using VS.Net 2005 RC (I think there is only 1) and thought to register my user controls in the web.config at the application root.

This worked fine until I thought it would be easeir to place my user controls in the same folder as the page(s) that use them most.

That did not work well at all. Try and compile and I get the following error:

The page '/Web/Plans/default.aspx' cannot use the user control '/Web/Plans/PlanList.ascx', because it is registered in web.config and lives in the same directory as the page.

Any pages that use the PlanList.ascx UserControl and reside in a different folder are not affected - its only the pages in the same folder as the user control.

BIZAARE.

Any thoughts?

Steve
October 21, 2005

# re: (PageIndexChanging not firing)

helli said:

>> ...The paging worked fine unless I try
>> to change from a page index > 0 to the
>> first page (pageIndex = 0). In that case
>> the PageIndexChanging event is not fired.
>> The same applied if I tried to go from the
>> last page to a previous page...

Is it possible that somehow the gridview's OnInit() method is not getting called? I had a scenario that manifested the same problem you're describing. My scenario was different in that I was subclassing GridView as a new control, rather than embedding it in a user control. The problem I had was occurring because I had forgotten to first call base.OnInit() in my subclass's OnInit method. Putting it in fixed the problem.

Steve

Ryan
October 26, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

You can get by withou the @register if you do the following.

-Put all of your User Control code inline.
-Put the .ascx file in the app_Code directory.

Hope this helps.. Living in Maui would help more.


Jacobus Terhorst
October 29, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Can you give me an example how to subclass a page?

Thanks

Colin
November 09, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

I concur with others: the new model really kills the flexibility of the system.

I've run into several other problems as well, one where I wanted to use a compiled assembly as an add-in to provide additional web pages to an existing application, and another where I wanted to apply field-level attributes to a Pages control declarations which, of course, aren't there anymore.

It seems to me that Microsoft now tightly coupled ASP.NET to a single process that doesn't fit all needs. I can see how you'd want some of the new features (as I DO think some are pretty cool), but it should have been an option not a mandate. After all, isn't a tenant of good design LOOSE coupling?

Fortunately there's a tool called MSBuild that is rumored to give you a little more control over the process given some extra configuration. With all the problems I'm having and some of my requirements, I'm chomping at the bit to use it!


Colin
November 09, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Just found out about something promising called "Web Deployment Projects":

http://aspadvice.com/blogs/ssmith/archive/2005/10/05/Visual_Studio_2005_Web_Deployment_Projects.aspx

Now to track down the add-in!

Christopher Steen
November 11, 2005

# Link Listing - November 11, 2005

A better BackgroundWorker : CancelImmediately and other
goodies [Via: Roy Osherove ]
A better Safe...

David Baker
November 11, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

The user control dynamic loading issue is really serious. I ran into this issue when the BETA was first released and never saw a very good way to resolve this.

It seems hard to believe that Microsoft could have "overlooked" this. Although I was on a Fritz Onion presentation regarding user controls and master pages where I posted a question about this. He was able to address the REGISTER part, but did not have an answer to the issue of dynamic loading.

The issue with using APP_CODE for user controls is that it doesn't work. You simply can't put a page in there or you end up with...
"The file '/x/App_Code/x.ascx' is in the special directory 'App_Code', which is not allowed."

I think Rick's description of making a "proxy" type stub class might be the only solid and logical way to make this all work. Which, in my opinion is something that the IDE should do for you.

Romi
November 21, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi,

My friend build a web site http://www.israelblessing.com with ASP DOT NET 1.1

My question is how difficult is it to convert the site to ASP 2.0?

Tanks,

Romi

Matt Vaughn
November 22, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

My impression is that the pendulum has "swung" to the other side...less sophisticated developers need tools to do more - too bad the outcome is "blackbox"...and no one can figure out what is happening and where the code is anymore.

I would recommend using a build tool like MSBuild or NAnt - "Code behind files are compiled into assembly and stored in the /bin directory. ASPX files are compiled on demand."

The Microsoft team in U.K. has released an awesome set of tasks for MSBuild (limited tasks by default). Over 100 tasks to build your application. This may provide the answer we are looking for.

See GotDotNet: http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=2cb20e79-d706-4706-9ea0-26188257ee7d

Rick Strahl
November 22, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Matt,

Microsoft has released the Web Deployment Projects Add-in which at least addresses the deployment issues.

http://msdn.microsoft.com/asp.net/reference/infrastructure/wdp/default.aspx

which makes use extensively of MSBUILD to provide the improved deploymnet features.

For the other things we're pretty much stuck with what Microsoft stuck in the box, unless we completely ignore the designer and continue to work the way 2003 worked (which is completely possible - just not with the designer).

Michael Salzig
November 29, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Can you give me an example how to subclass a page? Soory, I can't understand the page inheritance example.

Thanks,
Michael


K. Scott Allen
December 04, 2005

# The Great Migration

I popped into the&nbsp;Central Penn Code Camp this weekend and did a presentation on ASP.NET 2.0. There...

Stein-Tore Erdal
December 08, 2005

# Accessing public methods in Page and UserControl

I used to have public methods in my aspx.cs files.
In 1.1 I accessed these like this: ((MyPage)this.Page).MyPublicMethod().

To do the same in 2.0:
Create an interface in App_Code folder:
public interface IMyPage { void MyPublicMethod(); }
In MyPage.aspx.cs:
public partial class MyPage : Page, IMyPage
{
...
public void MyPublicMethod() { ... }
}

Then this works:
((IMyPage)this.Page).MyPublicMethod().



As for using dynamically loaded user controls:

I sometimes use a single aspx file and control the content by loading (using LoadControl()) one or more user controls depending on querystring etc... (I might have 20 or more user controls and using <%@ Register %> is not an option).

In 2.0:
I don't see any change when using LoadControl().
I am able to cast the return Control to the class of my user control. The only difference is that intellisense does not work for these.

Something I'm missing?

Stein-Tore

Stein-Tore Erdal
December 08, 2005

# dynamically loaded user controls

Important to load these in the Init event of the page or hosting control.
This applies to 1.1 as well.

Stein-Tore

Ian Nelson
December 10, 2005

# ASP.NET 2.0 - one month on

It's over a month now since Visual Studio 2005 officially RTM'd, and during that time I've been fortunate...

Steve West
December 13, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Thanks for the article.... man I gotta tell you Microsoft really F'd this one up. I think they are hiring morons now.

I can't believe that you can no longer setup namespaces for your forms and user controls and then declare those controls in the code behind or even build external classes to use as your base page to encapsulate functionality.

Maybe I'm missing something, but they said it is 100% backward compatible and that is completely false.

I need to be able to make a base C# class that is my "base page" then have my pages inherit from them. The C# class should be able to reference the user controls that may and or may not be dropped on the form. Then a property exposed to all the forms which inherit that form would then see those controls. So far I can't even figure out how to get a user control onto the page since none of the web forms even have a namespace to begin with. I tried to manually add my own namespaces but then it screwed things up.

I don't know why in the world MS moved away from allowing the ASP.net structure to work like the C# class libraries and other applications. Coming up with fancy "App_Code" directories etc is lame. The App_Code directory can't even see any of the forms in the other folders in the ASP.net application. That is idiotic if you ask me.

Does anyone else feel the same way about this? To me it would be like the US Military deciding to start up a horse cavalry unit, or issuing muskets to the guys in Iraq??!!?? Can anyone say bass akwards?

Rick Strahl
December 13, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Steve,

I agree. However, I think some of this is our own fault by not loudly enough complaining about this when we had the chance. This model was part of the original specification and very few people voiced any problems with this when it counted. I remember looking at this way back and thinking that this is a big problem and I was wondering why nobody was complaining about this... there was surprisingly little feedback on this when I posted about it too.

True, it ain't our job to do the beta testing for Microsoft, but we had a chance for feedback and we basically blew it.

It's interesting that NOW of course that ASP.NET 2.0 has shipped we hear a lot of those issues come to the forefront because people are actually doing real work with this stuff.






Steve West
December 15, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Rick,

I didn't spend that much time looking at the beta because I was busy making software. I didn't realize that they were basically throwing the baby out with the bathwater. What I don't get is why they made it less flexible.

I think I can find workarounds for most things except for one big thing.

We make an off the shelf product and we instruct customers that want to make changes to our app to make a new ASP.net project, then reference our single web app dll into their new project. If they want to add or change functionality they simply go to the ASPX page they want to change, then they make an new C# class in their new project that inherits our original form class. Then they change the directive on the ASPX page to look at their new class. In the new class they implement their changes. After that they have customized the app to suit their needs.

I am hoping if I choose one of the deployment methods that I can get a single assembly that they can do this functionality on.

Also I read in one of your other posts that you can do 1.1 style coding. If that's the case then perhaps I'm still ok, by not using partial classes at all. I have yet to test this to see if it works.

Rick Strahl
December 15, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

Yes if you don't use partial classes and you define all of your CodeBehind classes for controls and pages in APP_CODE instead then you can still reference the controls/pages directly. It's just not the default and you have to explicitly move the files there and reference only the class rather than the codebehind file.

Thinkest
December 20, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

You could also create a custom interface for your usercontrol in your App_Code the use the interface to access any additional properties or methods that you want.

Eric R
December 21, 2005

# re: Understanding Page Inheritance in ASP.NET 2.0

What is interesting is that Microsoft now has in Beta the Web Project Model option. Check it out here on Scott Guthrie's Blog: http://weblogs.asp.net/scottgu/archive/2005/12/07/432630.aspx

Here is an interesting line from the blog: '(note: yes, we made a mistake in not providing this choice in the first place).'

I must warn you as of today, this release isn't ready for primetime so be patient. But its on the right track

Kal Varnsson
January 06, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi guys. Great entry. I was banging my head against a wall thinking I was stupid. Why can't I access a user control class??? You've explained it well. MS are monkeys.

I've implemented an interface in the the APP_CODE directory, which is actually a nice solution cos I only need to do it for one control.

Some others have alluded to putting the code behind file in the APP_CODE directory. Does anyone know if this is possible?

Keith
January 09, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

I have the UC setup as a separate project in VS2005 so my solution has the aspx site with a separated UC set. I set the UC up as a sub site in IIS (created the actual app) and no problems. Probably does not work for everyone but I wanted to have my UC in a separate project for re-use purposes.

Teemu Keiski
January 12, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Equivalent of using @register in code is running the same through Page.ParseControl. Ugly as hell but seems to work,


Dim c As Control = Page.ParseControl("<%@Register TagPrefix=""rc"" TagName=""c"" Src=""subfolder/uc_subfolder.ascx""%><rc:c runat='server' />")
form1.Controls.Add(c)

# Teamwork: Visual Web Developer


Anand
January 18, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Is there any way for loading control dynamicaly

Jeff Dean
January 19, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

I ran into this problem when I tried to dynamically change master pages and set property values on the master page from the "child" page.

I fixed it by adding a reference in the page:

<%@ Reference VirtualPath="~/Master/Print.master" %>

While this is only applicable in certain situations (and since you would have to add a reference to every page/control you would like to reference), it still may help a little.

Pieter Siegers
February 01, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi Rick,

why is the code below correctly compiled but the control never added to the ASP namespace?

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="BuscAvanzado1.ascx.cs" Inherits="Usercontrols_BuscAvanzado1" %>
<%@ Register TagPrefix="uc2" Src="~/Usercontrols/test.ascx" TagName="Test" %>
<asp:panel id="pnlJFooter" runat="server">
<uc2:Test ID="test" runat="server" />
</asp:panel>

If I remove the nested usercontrol, it is added to the ASP namespace and I can dynamically add it in my Default.aspx. The nested control test.asmx was a usercontrol added without any modifications.

Any comment would be much appreciated!

TIA,
Pieter

Vishal Pawar
February 12, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Hey,

As u told for the controls in same directory u dont need register tag. I tried it but doesnt seems to be work.

Regards,

Vishal

Balaji Purushothaman
March 02, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

I was able to load the user controls using the following code, but don't know how to read those user entry after they submit the page.

Regards,
Balaji.

Steve West
March 03, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

It appears as though the Microsoft addition of the web application project, which is essentially what VS 2003 allowed will really enhance things. Currently I don't think that the new web site model is all that great. It seriously limits what you can do with inheritance within the forms.

For example, in VS 2003, we would create a base class within the web application, inherit from System.Web.UI.Page. In the base class, say MyApp.Site.Pages.DefaultTemplate or something like that would implement functionality based on controls that may and or may not be added. If the developer added a control to their page, the base page would see that the control was not null and would do what it needed to. In the web site project you would not be able to do this. The new web application project will allow this and from what I can tell you will still be able to selectively take advantage of the partial classes if you want.

So at any rate this really helps things. For some it may be more confusing, but for those of us who are pushing the limits we seriously need the web application project. Check out Scott Gu's site for more info!

http://webproject.scottgu.com/

Rick Strahl
March 03, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Steve,

No that is not correct. You can most certainly inherit from your own base class and define it on your partial class definition. VS full supports this too - but if you upgrade and have intermediary subclasses that don't live with the ASPX file, VS creates stub classes, so mayube that's what you're thinking of. However, if you do have the .cs file in the right place that stub is not required.

But I agree - there's a lot of confusion about how all of this works. If you run into any of these problems you really need to understand how ASP.NET brings all the pieces together which is a heck of a lot more complex than it was before.

But as an aside - subclassing pages visually in VS2003 was a royal pain in the ass too - if you needed controls in a subclassed visual form you had explicitly add them so the subclassed instance could see them - that hardly was ideal either <g>...

I do think that Web Application Projects brings the best of both worlds together. I'm working on a project with it right now and aside from a few minor operational issues it's working very well.

Steve West
March 05, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Rick,

One other question about this. The problem I think is that we weren't really trying to use visual inheritance, it was more for functional inheritance. For example, we created a user control Header.ascx and we created a class called DefaultTemplate.cs which inherited from System.Web.UI.Page. In DefaultTemplate we declared the header control on the page as protected. We did not place the control on the front page of the default template since it did not have one. Then in say a page load event we detect if the header is there, if so we perform work. If a programmer places the header control on their form, the base class did what it had to. I couldn't see a way of doing this at all in the web site project in VS 2005.

Plus on top of that the single assembly is critical for someone that buys our product and wants to override our behavior.

I know you can do a stub in the app_code, the problem is that the ascx class had to have a stub in there too to do that.

Also forms could not reference each other by type in the web site since there was no visibility of each form to another form.

Will the web application project allow all of these things to occur like the VS 2003?

Thanks for your research into this, it has been a HUGE help.

Steve

Brian
March 05, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

The way this new functionality works is going to force my web/UI designers to use VS2005 (some of which are using macs). Previously I could do a release of .aspx files and the one .dll to the staging server, and they could go in after the fact and clean up all the html in the .aspx pages.
Then they would check in all their changes to source control. Now that the .aspx page has a dynamic Inherits="Default.aspx, aasd63hddv" after compile, they will have to merge any changes they made to the deployed version into the source control version - what a headache!! If they accidentally check in the version with the unique Inherits="Default.aspx, aasd63hddv", then it will break VS2005 IDE the next time someone does a 'get' from vss. =\

Brian
March 05, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Oops, my previous post was supposed to go on one of your other blogs about the 2005 pre-compilation model.

# Web Form Inheritance in .NET 2.0

Because of the changes to the compilation model and structure of aspx pages in .NET 2.0, page inheritance...

Larry
April 04, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

"This is a pretty major change in the way ASP.NET works. There’s a workaround for this, but it’s not pretty"

I can't seem to put a page reference in app code. How do I put a textbox on a form and then create a public property that allows me to set the text value for instance?

Or are you saying I have to dynamically construct the page in app_code? That seems pretty major.

Larry
April 04, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

nm think I got it. Just have to make a class with overridable members and then override them in the actual page. MustInherit and MustOverride seem to provide a nice mechanism for this.

Ben Parrish
April 07, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

You can still access user controls programatically. To do so you have to do two things:

First, in the User Control file, add a ClassName to the Control definition. For example:

<%@ Control ClassName="KeywordSearchResults" Language="VB" AutoEventWireup="false" CodeFile="KeywordSearchResults.ascx.vb" Inherits="UserControls_KeywordSearchResults" %>

Second, in the page you want to use the control in, add a Reference declaration, as follows:

<%@ Reference Control="~/UserControls/KeywordSearchResults.ascx" %>

Then, whenever you want to use the control in code, declare it as follows:

Dim Results as ASP.KeywordSearchResults (all user controls are compiled to the ASP namespace, I think. Not certain).

Anyways, I tried that and it worked for me. Enjoy.

Rick Strahl
April 07, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Ben, if you'd read through the comments (and the article actually <g>) you'd see that we've already discussed using the @Reference tag on the page. The issue is if you don't know what you're referencing until runtime in which case you CAN'T use this tag on a page or control.

Rexiology::Work
April 16, 2006

# Where is [file].aspx.designer.cs in native VS2005 Web Project?

&nbsp;
Just had a further reading of the migration from ASP.NET 1.1 website to ASP.NET 2.0 one. ScottGu's...

Rexiology...
April 16, 2006

# Where is [file].aspx.designer.cs in native VS2005 Web Project?

&nbsp;
crosspost from http://rextang.net/blogs/work/
Just had a further reading of the migration from...

andcerve
April 20, 2006

# Partial classes for codebehind in ASP.NET 2.0

Hi guys!
Nice stuff here!!

I have a question.
Suppose I have a myPage.aspx like this:
<%@ Page Language="c#" AutoEventWireup="true" CodeFile="myPage.aspx.cs" Inherits="myPage" %>

and I have the myPage.aspx.cs like this:

public partial class myPage: System.Web.UI.Page
{
...

private int intero;

private void Page_Load(object sender, System.EventArgs e)
{
ciccio();
}
...
}

Now suppose that I want to define the ciccio() method into another file called myPage2.cs (at the same level of myPage.aspx.cs, not in App_Code!) where to put another piece of the myPage partial class. Here it is:

public partial class myPage
{
...
private void ciccio()
{
...
}
...
}

Why do I get the compiler error "The name 'ciccio' does not exists in the current context" ?!
Even the intellisense doesn't show the ciccio() method from inside myPage.aspx.cs !!

But, strange thing, the private variable intero defined in myPage.aspx.cs is perfectly visible from inside the myPage2.cs !!

If I try to put the myPage2.cs file in App_Code then the problem persists and even the intero variable is no more visible!!!

Can someone help me? PLEASE?!?

Thanx in advance.
Bye,
andcerve

Dominic Turner
April 28, 2006

# Doing @Register tags in code

Am a bit stuck with the "loading user controls dynamically part" - as it seems a real limitation that the tag prefix must be registered in the page.

This kind of stops the "portal" type of development.

However from a link here by Tim Farley I saw that you can access the controls element / tagprefix collection for pages - this shows a way of doing it possibly?


' Create a new TagPrefixInfo object.
Dim tagPrefixInfo As System.Web.Configuration.TagPrefixInfo = _
New System.Web.Configuration.TagPrefixInfo("MyCtrl", "MyNameSpace", "MyAssembly", "MyControl", "MyControl.ascx")

' Execute the Add Method.
pagesSection.Controls.Add(tagPrefixInfo)

' Add a TagPrefixInfo object using a constructor.
pagesSection.Controls.Add( _
New System.Web.Configuration.TagPrefixInfo( _
"MyCtrl", "MyNameSpace", "MyAssembly", "MyControl", _
"MyControl.ascx"))


http://msdn2.microsoft.com/en-us/library/system.web.configuration.tagprefixcollection.aspx

Dominic Turner
April 28, 2006

# Doing @Register tags in code

C#:

// Create a new TagPrefixInfo object.
System.Web.Configuration.TagPrefixInfo tagPrefixInfo =
new System.Web.Configuration.TagPrefixInfo("MyCtrl", "MyNameSpace", "MyAssembly", "MyControl", "MyControl.ascx");

// Execute the Add Method.
pagesSection.Controls.Add(tagPrefixInfo);

// Add a TagPrefixInfo object using a constructor.
pagesSection.Controls.Add(
new System.Web.Configuration.TagPrefixInfo(
"MyCtrl", "MyNameSpace", "MyAssembly", "MyControl",
"MyControl.ascx"));

Matt Colin
May 02, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi, I have been working on upgrading our site, Samtec.com for about 2 weeks now. It's very extensive and I have run across a lot of errors. The only one I haven't seemed to be able to fix is the issue with what i've seen above with the user controls and aspx pages that need to be types. I am developing in VB however so the C# equivalents are differen't and I haven't seemed to be able to figure out the APP_Code folder. I did what I interpreted from the limited example and found that I received the error: "The file '~/App_Code/x.ascx' is in the special directory 'App_Code', which is not allowed."

So if there is anyone that could help me in this matter I'd really appreciate it. I'm basically sitting in hell right now trying to figure it out. A detailed example might help....


Priya
May 03, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi, I have a composite control with a button. The button click event gets called from the aspx page. But, if I bring the aspx page under a master page, the button click event doesnt get called. Can anyone please help me with this?

Matt Colin
May 04, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

I'm not sure but I ran into this a lot. Check your <form> tags. Is the button on the control page a regular html input button? Just a though.

Michael Knopf
May 12, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Hello All

I have been feeling your pain, I just got started with 2.0 two weeks ago after 4 years of full time VS 2003 work. I have been pulling my hair out over the many issues the new framework introduced. Fortunitely this past Monday, May 8th, the Microsoft team released a new asp.net project template called the "ASP.NET Web Application" which solves ALL of the issues reported in this blog (well at least they say it will). You can get the details at http://weblogs.asp.net/scottgu/archive/2005/12/07/432630.aspx and http://weblogs.asp.net/scottgu/archive/2006/05/08/445742.aspx and you can download and install the new project template at http://msdn.microsoft.com/asp.net/reference/infrastructure/wap/default.aspx Hope this helps all of you.

Malcolm Stitt
May 17, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Great blog, thanks!
Michael Knopf's reference to the new asp.net web application model did the trick. My web app which uses many usercontrols is working fine. Now I can gradually adopt the new model, rather than at least 1 month worth of rewrites on my own dime.

Still one big questtion to me is the following:

How do you reference a usercontrol's type from common code that is outside of a web page? This came up in an sql statement builder that I wrote which walks the control list of a datagrid, and looks for data entry controls. It is your typical CommonLib component which is very necessary.

Inside the function I have the following logic:

'here is a rough, simplified sketch of what I am doing in a common shared function

dim ctl
dim listofvals as string = ""
while ....
ctl = next control in collection
dim ctltype as string = ctl.GetType.Name
Select Case ctltype
Case "TextBox"
dim tb as textbox=ctl
listofvals=listofvals & " " & tb.text
Case "DateEntryControl_ascx"
' *** error the following user control type can't be found
Dim datectl As DateEntryControl = ctl
Dim strDate = datectl.theDateValue
listofvals listofvals & " " & strdate
end Select
end while

No matter which folder I place my DateCtl.ascx web control in, I can't get get visibility to it.

It worked so well in 1.1 !!
Any ideas??
thanks














Rick Strahl
May 17, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Malcom with standard ASP.NET projects you can't cast like that unless you add the @Register tag to the page and reference the DateEntry UserControl.

With WAP you should be able to reference the codebehind class as you are doing the same way as in 1.1. If you're using WAP make sure you page has been converted to a WAP page (ie. it has the CodeBehind directive instead of CodeFile - otherwise it still runs as a standard 2.0 page).

Malcolm Stitt
May 17, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Thanks Rick,
It is really too bad that WebUserControls can't be treated the same as built in controls like TextBox. They were that way in 1.1. I was able to walk a datagrid's controls and typecast the control back to its type via its typename. This saved me thousands of lines of code writing (checked) datagrid values back to the database.

Internally, Microsoft does treat them the same in some places. They have no trouble creating a DataGrid control collection that contains builtin controls and usercontrols, and seem to understand the properties of each usercontrol.

When I first saw the 1.1 model I was very impressed that an object was an object. In 2.0, this seems to have run clearly amock. My brain is ready to pop just figuring out what folder to put stuff in.

thanks again & great web site



Malcolm Stitt
May 18, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

So, maybe this is starting to make some sense.

It looks like WAP comes in handy when you create a WebUserControl that will need to have its properties accessed by shared code that lives outside of a web page.

Typical code that needs this access could be something like a Myprintf() method, or in my case a BuildSql() method that lives in a commonlib. These functions need to understand the data structure that lives inside the web control so that they can access the data content.

Sound right?

So, is there a reason why I should not build all of my webusercontrols as WAP, and everything else using the newer partial class model?

Aren't we really just missing a c++ "friend" declaration to make this whole issue go away?

thanks




Rick Strahl
May 18, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

How are you going to mix and match to Web projects? Unless I'm missing in what you're saying you can't do that.

It's not just user controls. It's other Pages, Masters - anything that has declarative markup suffers the same issues in standard projects. Unless you add a @Register or @Reference tag the codebehind classes cannot be found.

I don't see any reason why you'd want to stick with stock projects if you run into this particular problem.




Nilesh
June 01, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

I have read all the posts on this page, but I'm still stuck at a particular issue.

1. I created a "Web Site" project with VS2005.
2. I created a control extending the LinkButton control.
3. This control is in a namespace "abc.Controls"
4. I created a page, which is in the namespace "abc.MyPages"
5. I tried to include the control that I created in this page, using the @Register tag. I provided the Assembly name as "abc".

The code wont compile. It says "could not load file or assembly 'abc' or one of its dependencies"!!

What gives? Any thoughts would help.

Cheers

Nilesh
June 01, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Ah well, found the answer.
I am not supposed to include the assembly name in the @Register tag because it automatically compiles the code for the control if it is in the App_Code folder.

Cheers

Daniel
June 13, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Apparently Microsoft is aware of the problem. a new web appliation model has been introduced:

http://msdn.microsoft.com/vstudio/default.aspx?pull=/library/en-us/dnvs05/html/WAP.asp

for those who are suffering from various wired bugs after migrating your web app from 1.1 to 2.0, download the new web application model and install as your visual studio 2005 plug-in,
you will laugh !




joseph george
July 15, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Pls note that for Page Inheritance, you will most likely have to add this clause to the Page directive of the inherited page:
CodeFileBaseClass="BaseClassName"

Rick Strahl
July 15, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Joseph, unfortunately CodeFileBaseClass works only with pages that are reference with the CodeFile= attribute. If you have a base class in App_Code (or in another assembly) you can't reference CodeFileBaseClass...

leemarge
August 15, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

as an alternative to adding the tag prefix line to the page, i found i just had to add a using statement in the code behind page to the namespace containing the user control i wanted to load dynamically. this seemed stupid because the user control i was loading dynamically resided in the same namespace as the control trying to load it, but without the using statement it failed to load, with it it worked. job done.

Torna
August 26, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

in child.aspx file
<%@ Reference Page="~/BasePage.aspx" %>
<%@ Page CodeFileBaseClass="BasePage" ...

then you dont need to save base clas in App_Code

Joe Hardy
September 13, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Hey - check this out! I rather get the impression that this will cut the mustard for programmatically loading controls, no?

http://msdn2.microsoft.com/en-us/library/system.web.configuration.tagprefixinfo.aspx

I'm just about to give it a stab...

Rick Strahl
September 13, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

Hmmm... that deals with configuration sections in web.config basically. This means you still have to know what you want to add and then you have to restart the app because this modifies web.config. I don't think this is going to work for a dynamic solution...

Joe Hardy
September 13, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

I got the impression that it wasn't doing that owing the following in the documentation:

"The TagPrefixInfo class allows you to programmatically access and modify tag-prefix information stored in a configuration file. It provides the same functionality as the ASP.NET @Register directive. "

Or am I missing something?

john joseph
September 22, 2006

# how can i access properties and methods of dynamically added controls

how can i access properties and methods of dynamically added controls?

Web Forms
September 25, 2006

# ASP.NET Forums - reference the parent page from a user control in asp.net 2.0?


Web Forms
September 27, 2006

# ASP.NET Forums - Dynamic control loading


Channel 9: Techoff
September 28, 2006

# Case of the Missing Namespace


Rick Strahl
October 03, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

A more completel article on compilation and deployment is available here now:

http://www.west-wind.com/presentations/AspNetCompilation/AspNetCompilation.asp

eggheadcafe.com articles
October 04, 2006

# aspnet Accessing _Default page from a child derived from UserControl (Express 2005)


Channel 9: Techoff
October 07, 2006

# Re: Case of the Missing Namespace


Web Forms
October 14, 2006

# ASP.NET Forums - Accessing a UserContol's custom properties in a regular class (not a page class)


Rick Strahl's Web Log
October 15, 2006

# New Compilation Modes in ASP.NET 2.0 - Rick Strahl's Web Log

In this entry I'll take a close look at the new Compilation models in ASP.NET 2.0. On first sight I think that these new models are more cumbersome than version 1.x for most common deployment scenarios, although they do offer new and secure ways to deploy a site. It will take some time and experimentation to find what works best...

Architecture
October 25, 2006

# ASP.NET Forums - System.Web.UI.UserControl scope question

# DotNetSlackers: Understanding Page Inheritance in ASP.NET 2.0


ASP.NET 2.0 Tricks And Tips
November 08, 2006

# ASP.NET 2.0 Tricks And Tips: June 2006


ASP.NET 2.0 Tricks And Tips
November 16, 2006

# ASP.NET 2.0 Tricks And Tips: Multiple pages accessing the same codebehind file in ASP.NET 2.0


RunFrazer
November 25, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

I have found that you don't need <%Register %> on each page if you you have put the user controls in a subfolder.
But what you do need to do is load your user control in the Page_Init event.
Alos if you wish to extend or set any properties you will need to do that in the Page_Init of the control.

# Google Groups: microsoft.public.dotnet.framework.aspnet


mm
December 15, 2006

# re: Understanding Page Inheritance in ASP.NET 2.0

I still can't find anything!!! Partial Classes really confuse the issue about what is going on. Now most of the code generation of 1.1 is gone. And the help is more sparse and confusing than ever.

I'm going back to the command line compiler now...

Installation and Setup
January 05, 2007

# ASP.NET Forums - Help w/web.config files

# ASP.NET Forums - ....allready contains a definition for...


SnowDragon
January 12, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

If someone has alreeady posted this solution let me appologise. I don't have time to read all of the comments here, but have solved the Web Control problem for my web app which is built entirely on programmatically included controls.

I was having the sam problem as described in the articla after moving to .NET 2.0, but only for some of the controls being imported, others were working fine. I now know why and this is the solution:

Where you need to dynamically include a webcontrol, build it an interface declaring all of the properties you need to set. You can then use the following example (taken from working code):

System.Web.UI.Control thisSub = LoadControl("menusub.ascx");
MenuSub.Controls.Add(thisSub);

// Set the values for the sub menu
((Combined.Interfaces.IMenu)thisSub).ParentPage = Convert.ToInt32(result["Parent_ID"]);
((Combined.Interfaces.IMenu)thisSub).User = this.User;


Where IMenu is the interface inherited by the menu sub control. This will compile and run fine in .NET 2.0.

Hopefully this has helped.


January 27, 2007

# Bily - 博客园


Madushan
February 09, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

hi this was helpful for me. thanks.
im interested about these oop concepts.

regards,
madu

David Wong
February 15, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Having read through this article and comments, which was extremely informative, I'm not sure if my problem is related. I'll attempt to describe it.

On a page I have a gridview and I'm dynamically creating other gridviews. In these gridviews I'm creating templates, using a class that implements ITemplate. In this Template there is a linkbutton, that is also being created dynamically I'm hooking up it's click event to a procedure in the Template Class. The procedure then executes some code and references a public procedure in the page class. This compiles and runs fine. When I click on the linkbutton it executes up to the point where the public procedure in the page class tries to access any controls, ie. the static gridview, or even the response object at that time.

The error message I recieve is a 'Object reference not set to an instance of an object.' Which is the static gridview.

Taking a guess I think the template class is holding a new object of the page class and not a direct reference to the one that is created initially.

Any thoughts would be much appreciated.


February 21, 2007

# ASP.NET 2.0 Learning Guide

# Grupos do Google: microsoft.public.dotnet.framework.aspnet


Stormy
March 29, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Great article and very important.

First, as has been mentioned, if you want to add usercontrols dynamically, you still would need to add the Reference to that control at the top of your web page. I would add all of your usercontrols as references in your page so no matter what you add at runtime, its referenced. Sucks but thats all you can do...

Second, this problem of talking to UserControls from the Master is difficult and Im very disappointed with Microsoft's .NET team on this point as well, due to how they architected the dynamic assembly and removal of page namespacing. They now say that there is a performance hit accessing usercontrols stored in a masterpage accessed from the page itself, so go figure? How are we supposed to pass values to UserControls from our pages now? Ive got a solution.....its still pretty reliable, but performance-wise Imnot so sure. If anyone wants to know how to do that, Ive found two ways (other than the very lame "stub" page solution). Both require you have the @reference to the control you are accessing in your MasterPage at the top of your aspx page:

option one:

Add this to your Web Page:
<%@ Reference Control="~/YourUserControlName.ascx" %>

In your pages codenehind:
YourUserControlName TheControl;
TheControl = (YourUserControlName)((YourMasterPagesClassName)Page.Master).FindControl("YourUserControlNamesID");
TheControl.YOurUserControlsProperty = "HelloWorld";


Option Two:

Add this to your Web Page:
<%@ Reference Control="~/YourUserControlName.ascx" %>

In your pages codenehind:
YourUserControlName TheControl;
TheControl = (YourUserControlName)((YourMasterPagesClassName)Page.Master).YourUserControlName;
TheControl.YourUserControlsProperty = "HelloWorld";

* In this case, in your MasterPage, add your UserControl as a property of the MasterPage control as follows:

public YourUserControlName PageBodyMenu {get {return YourUserControlNamesID;}}

Note: The UserControlNamesID is actually the id on that usercontrol in the MasterPage itself.


- stormy

Rick Strahl
March 29, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Using a MasterPage as a control container might let work reasonably well to hold all your references and expose them. But that still causes some issues if you have lots of controls you need to load dynamically.

Not sure about the perf hit - I can't imagine what the perf hit could be given that a Master Page is really nothing more than a control loaded on the page.

Stormy
March 30, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Rick, one other trick I did today in a site Im building that might help you with the erefernce issue loading UserControls dynamicallin from a page.

I went in and created an old-fashioned "include" in my ASP.NET 2.0 web project like so:

<!--#include virtual="~/UI/UserControls/UserControlReferences.inc"-->
.

Inside the .inc file I drop in my references to UserControls:

<%@ Reference Control="~/UI/UserControls/PageHeadBuffer.ascx" %>
<%@ Reference Control="~/UI/UserControls/PageHeadCache.ascx" %>
<%@ Reference Control="~/UI/UserControls/PageHeadDoctype.ascx" %>
<%@ Reference Control="~/UI/UserControls/PageHeadMetatags.ascx" %>
<%@ Reference Control="~/UI/UserControls/PageHeadJavaScript.ascx" %>
<%@ Reference Control="~/UI/UserControls/PageHeadSkin.ascx" %>
.


My web page has the include at the top of the aspx page and now everyplace that include is found, all those pages share a family of UserControl references they can access. No performance hits I can see. Catch is this "include" cannot be .aspx or user control page. Nor can you do this insider the MasterPage. I used a simple .inc file like we used to use in old ASP VBScript of days gone past. Worked great! Allows me to centrally manage all UserControl or other references used in my site for all pages that have the include. Now at least you can dynamically load a family of controls and not worry about the reference problem for those usercontrols that you have prebuilt in your web project.

- stormy, www.stormdetector.com

Web Forms
April 23, 2007

# ASP.NET Forums - Web Page Inheritance


Web Forms
April 24, 2007

# ASP.NET Forums - .cs file not in sync with .aspx


Vishwa
May 02, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi Stormy,

why don't you add your usercontrol references in your web.config

<system.web>
<pages theme="DefaultTheme" >
<controls>
<add tagPrefix="ctl" src="~/Pagelets/Menu.ascx" tagName="Menu"/>
</controls>
</pages>
.
.
</system.web>

Rick Strahl
May 03, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

That's not really the point. If you know which controls you're going to use you can easily register them on the page. The point is for dynamic invokation when the control type isn't known.

pure dynamic controls
May 08, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Control FeaturedProductUserControl;
FeaturedProductUserControl = LoadControl("TC-General.ascx");
FeaturedProductUserControl.ID = "MyUC";
PlaceHolder1.Controls.Add(FeaturedProductUserControl);

i want this ... but i cant get its properteis/method at runtime plz help me

ASP.NET Forums
May 18, 2007

# Accessing a UserContol's custom properties in a regular class (not a page class) - ASP.NET Forums


ASP.NET Forums
May 18, 2007

# Web Page Inheritance - ASP.NET Forums


ASP.NET Forums
May 20, 2007

# reference the parent page from a user control in asp.net 2.0? - ASP.NET Forums


KJ
May 21, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi,

Could any one post sample code for page inheritance or any source links also fine.

Thanks,
KJ

ASP.NET Forums
May 29, 2007

# .cs file not in sync with .aspx - ASP.NET Forums


ASP.NET Forums
May 30, 2007

# ....allready contains a definition for... - ASP.NET Forums


ASP.NET Forums
June 05, 2007

# VS 2005 code compatibility - ASP.NET Forums


ASP.NET Forums
June 11, 2007

# Dynamic control loading - ASP.NET Forums


ASP.NET Forums
June 18, 2007

# Help w/web.config files - ASP.NET Forums



June 19, 2007

# ASP.NET 2.0 Learning Guide


gazeteler
June 30, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

I think Rick's description of making a "proxy" type stub class might be the only solid and logical way to make this all work. Which, in my opinion is something that the IDE should do for you.

ASP.NET Forums
July 04, 2007

# System.Web.UI.UserControl scope question - ASP.NET Forums


Anatoly Lubarsky
July 12, 2007

# Anatoly Lubarsky : Asp.Net 2.0: Rick Strahl talks about Page Inheritance


ASP.NET Forums
July 17, 2007

# RadioButtonlist server control - ASP.NET Forums


Subhash
July 19, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi,

i just created a new website in .NET 2.0 and for the default when i include a namespace it is throwing the following error. what am i doing wrong. this happens even for any new webform also.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace subhash
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
}
}

the errors are like this
Error 1 'ASP.default_aspx.GetTypeHashCode()': no suitable method found to override c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\studentactivities\5ce02ada\f713f29a\App_Web_sgl2j8g7.2.cs 289
Error 2 'ASP.default_aspx.ProcessRequest(System.Web.HttpContext)': no suitable method found to override c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\studentactivities\5ce02ada\f713f29a\App_Web_sgl2j8g7.2.cs 293
Error 3 'ASP.default_aspx' does not implement interface member 'System.Web.IHttpHandler.IsReusable' c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\studentactivities\5ce02ada\f713f29a\App_Web_sgl2j8g7.2.cs 129
Error 4 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). C:\Documents and Settings\subhash.m.NUWARE1INDIA\My Documents\Visual Studio 2005\WebSites\StudentActivities\Default.aspx.cs 14 33 C:\...\StudentActivities\

eric
July 20, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

hey rick,

i actually have a similar question to one posted by matt a while ago that was never really answered. i created the app_code folder and placed my usercontrols into it... but when i try to run the page, i get the error 'the file ~/App_Code/itemlistplate.ascx is in the special directory App_Code, which is not allowed.' why wouldn't this be allowed, and do you know how to fix it?

thanks,
eric

Peter Alvin
October 26, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

I think there is a bug in C# page inheritance.

As soon as I try to inherit from another page like thus:

public partial class _Default : PageBase // System.Web.UI.Page


I get this error message, even though PageBase is another page in the SAME project:

Error 1 The type or namespace name 'PageBase' could not be found (are you missing a using directive or an assembly reference?) C:\src\Io2\Default.aspx.cs 14 33 C:\src\Io2\

Any ideas?

Rick Strahl
October 27, 2007

# re: Understanding Page Inheritance in ASP.NET 2.0

Page classes are not visible to other pages unless you define them explicitly in App_Code. So for any shared pages define the code behind file App_Code and then it should be visible to your inherited pages.

Sagi
January 05, 2008

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi Rick,

Putting codebehind of usercontrols in some folder in app_code sounds great. though .net 2 just wont allow it. It gives this error:
'the file ~/App_Code/UserControls/usercnt1.ascx.cs is in the special directory App_Code, which is not allowed.' if changing the usercontrol's codebehid filename to usercnt1.cs instead of usercnt1.ascx.cs still this error.

Is there any way to avoid this error?

Thanks,
Sagi

Crystal Brite
January 17, 2008

# re: Understanding Page Inheritance in ASP.NET 2.0

I am trying to implement a user control and receive the error "invalid value for the tagname attribute". What exactly is the purpose of this attribute? Please?

CodersBarn.com
June 01, 2008

# ASP.NET: Web Site versus Web Application Project

ASP.NET: Web Site versus Web Application Project

CodersBarn.com
June 03, 2008

# ASP.NET: Web Site versus Web Application Project

ASP.NET: Web Site versus Web Application Project

Mike Otten
June 26, 2008

# re: Understanding Page Inheritance in ASP.NET 2.0

From the article:
> you can step through code, find a problem, fix it in the editor and simply re-run the page.

I'd love to sign up here! When I launch something in debug mode, all my code pages are read only so my edits require stopping the debugger, editing, recompiling, and then either refreshing the browser or relaunching the debugger (both seem to take pretty long).

Related: my code-behind edits seem to require project re-compilation in order to see their effect(s).

Thanks for any tips/pointers/maps to the promised land! ;)

Rick Strahl
June 26, 2008

# re: Understanding Page Inheritance in ASP.NET 2.0

That's due to Edit and Continue which causes some files to be locked while debugging (in C# at least). It's idiotic so I tend to never use Edit and Continue in Web projects. It's just a weird way to work. If you're using Stock ASP.NET Projects Edit and Continue isn't all that useful anyway as you can make page and codebehind changes and see them on the next hit even when the debugger is attached anyway.

John Welborn
September 02, 2008

# re: Understanding Page Inheritance in ASP.NET 2.0

I'm surprised at how often I randomly google for an issue / solution and I'm pointed to good ole' west-wind.com. :) Cheers for the consistently great content. Look at the lifespan of this post!!! Coming up on the 3 year anniversary!

In other news, I've had a page working using the @Register directive and LoadControl to create pseudo dynamic controls (meaning I know which types of controls are going to be available on the page, just not the number or order) and it was all working well.

Then I realized, I wanted to use the same control creation logic on another page... so I set about moving the code into a separate class. That's where i started having problems.

        public static void addControlTextBox(Control container)
        {
            ASP.FieldControlText tc;
            tc = (ASP.FieldControlText)LoadControl("~/Controls/FieldControlText.ascx");

            container.Controls.Add(tc);

            // more settings and code below....
        }

The above code was working at the page level... but now that I've tried moving it into a class in the app_code folder (just using public static methods), I'm getting the following error on compilation:

The type or namespace name 'ASP' could not be found

I think I vaguely understand why... but due to the aforementioned vaguery I can't figure out what to do from here other than start random massive changes or duplicating the code to the new page. Any help?

Also... as a sub note... these user controls were built with the old west-wind data objects. I'm going to update them to use the standard dotnet controls and the new wwDataBinder if I can figure out this part.

Thanks in advance.

Yuliya
October 01, 2008

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi,
I was reading posts on this web site but I do not still understand how to implement web from inheritance in ASP .Net 2.0. I tried using App_Code but could not get controls from the base form to show on the inheritted form.

What I need to do is to inherit base form that contains controls (text box field, etc.) and be able to see those controls on the inheritted form when I load that form in the browser.

How do I get controls from the base form to show on the inheritted form? Is there place where I can download a sample project that is using ASP .Net Form inheritance?

thank you
Yuliya

m9525
October 11, 2008

# re: Understanding Page Inheritance in ASP.NET 2.0

But I can inherit a web form to another web form. My base page even has a master page. Don't think it has anything to do with using .NET 3.5 VS08

I create BaseClass.aspx and BaseClass.aspx.cs inside App_Code, and interface for them also in App_Code

-----------------
public partial class BasePage : System.Web.UI.Page
    {

        protected IComponentEditor Editor;

        protected IBaseMasterPage BaseMasterPage
        {
            get
            {
                return (IBaseMasterPage)Master;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
// some code
        }


        /// <summary>
        /// Set generic properties of IComponentEditor
        /// Boxing will occur later after InitializeEditor()
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
// some code
        }

// some event used in Init or Load
        protected void BasePage_ActiveComponentChanged(object sender, net.clara.webconsole.ActiveComponentChangedEventArgs e)
        {
// some code
        }
    }

}


And the aspx one is one-liners
<%@ Page Language="C#" MasterPageFile="~/mymaster.master" AutoEventWireup="true" CodeFile="BasePage.aspx.cs" Inherits="BasePage" %>


Here is sample of child where Init and event will be taken from parent:

public partial class AccountMenu : BasePage
{
    protected new void Page_Load(object sender, EventArgs e)
    {
       // blabla
        this.Editor = this.ControlEditor;
        base.Page_Load(sender, e);        
    }   
}


And child's aspx:

<%@ Page Language="C#" MasterPageFile="~/mymaster.master" AutoEventWireup="true" CodeFile="AccountMenu.aspx.cs" Inherits="AccountMenu" %>

<%@ Register Src="controls/customercomponent.ascx" TagName="customercomponent"
    TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentEditor" Runat="Server">
    <uc1:customercomponent ID="ControlEditor" runat="server" />
</asp:Content>


So far works fine...

Kostenloser WEB Space
December 25, 2008

# Kostenloser WEB Space

Archiv aus Deutschland und aller Welt mit Informationen und Links zum Empfang von Webradio, Web-TV

Dr Evil
January 28, 2009

# re: Understanding Page Inheritance in ASP.NET 2.0

I too am using Master Pages, and also want to setup a 'base' page from which other concrete pages can inherit - all referencing the master page.

The issue I found was that the 'base' page class couldn't see my custom master page as I'd placed it in APP_CODE.

The solution was to add a skeleton BasePage.aspx which contains the
<%@ Page... %>
and the and associated code-behind. This way the base page can contain common code which references the master page and it's controls.

This gave rise to another issue... my BasePage.aspx was now visible on the website, and could be navigated to directly. I got round this by setting a specific location in the web.config which denies access to this page...

  <location path="BasePage.aspx">
    <system.web>
      <authorization>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

Dr Evil
January 28, 2009

# re: Understanding Page Inheritance in ASP.NET 2.0

Scrub that. Everything was fine 'building' - as soon as i 'RE-build' i get issues with unrecognised type names again - putting in APP_CODE and using the IMyMasterPage Interface seems to be the only way.

Bruce
November 19, 2009

# re: Understanding Page Inheritance in ASP.NET 2.0

Thank you, thank you, thank you ...
our issue was based on this and it was driving me nuts!
Our usercontrols are not created on the fly in the code, we insert them on the page using <%@ Register and our usercontrols (.aspx.vb) inherit from a baseclass.
When the page loaded, our dropdown would be empty but if we debugged and looked at the control, it was being populated??
It turns out that once we used CodeFileBaseClass in the @control directive of our usercontrol to point to our base class, it worked.

aniket
January 27, 2010

# re: Understanding Page Inheritance in ASP.NET 2.0

Hi,

I have a different kind of a problem. I have an ASPX page with no code behind having server controls, HTML controls in the page. I want to access the ASPX and load only the designer HTML and the code behind need not be loaded.
I want to access the members of all of the controls in WinForm application. So is this a valid scenario using any of the .Net framework classes? Or do I have to manually parse each line, load the individual control based on the text and then load the members?

I have been pondering over this issue for long time, help required. Its too much to parse each control based on the text in ASPX page.

thanks,

CodersBarn.com
May 24, 2010

# ASP.NET: Web Site versus Web Application Project

ASP.NET: Web Site versus Web Application Project

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024