A couple ASP.NET lessons learned

From .Net Guy:

I'm in the middle of the laborous process of writing an article (or, more likely, a series of articles) for my web site about ASP.NET Tips and Tricks.

We have a lot of lessons we've learned from bending and breaking ASP.NET, especially as it pertains to writing custom server controls. Here's a couple quick ones that I keep banging my head against:

1. Put controls in the tree as soon as possible.

A lot of things happen when the control is in the tree; namely, you get access to events, you can reference your parent Page, you can retrieve your unique client-side ID, etc. The longer you're not in the tree, the longer you have to wait for access to those things (in one example I'm struggling with today, I need the client ID but I can't find it). If a control needs these things, then it needs to be in the tree as quickly as possible.

2. Separate rendering from the child control tree.

When making a server side control, the child control tree gives things access to the events and pages and client IDs, as seen in #1. However, I've found it to be a mistake to simply create the entire child control tree with EVERYTHING you plan to render. Most often, this can be almost impossible to achieve in the face of postbacks, because your child control tree might be changing as a result of the work done during postback. Just as important for events, this child tree needs to reflect the exact same during repeated postbacks so that events are sent to the right control. Change the tree, and the IDs change, and your button click may end up sent to the wrong button!

So my recommendation here is to only put things into the tree that have a need to be there -- controls that render data and receive events -- and to leave the actual physical rendering of the layout of the tree. The things in the child control tree don't even necessarily need to be rendered.

Writing server-side controls is very difficult if you wish to do it well. You cannot ignore the reality of the fact that there's HTML underneath, and that this UI doesn't really function like a traditional rich UI.

No Comments