views:

330

answers:

1

I would like to intercept the OnInit of (numerous) controls on a page. The purpose is to set various properties of the controls at run time. It is critical that the interception happens prior to the start of ViewState tracking for the control because the property values in question are not to be stored in the ViewState (to conserve space).

There are many simple techniques to set properties at run time, but they do not meet my needs because they happen after ViewState tracking for the Control starts. (An example of one such technique is looping through the controls in the Page's control tree during the Page's OnInit method. This is too late as ViewState tracking has already started on the controls as they were added to the tree.)

I came close to a perfect solution. I put the following in a .browser file:

<browsers>
    <browser refID="Default">
     <controlAdapters>
      <adapter controlType="System.Web.UI.WebControls.WebControl" adapterType="TestClassLibrary.TestWebControlAdapter, TestClassLibrary"/>
     </controlAdapters>
    </browser>
</browsers>

The following is the source code for TestWebControlAdapter:

using System;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Adapters;

namespace TestClassLibrary
{
    public class TestWebControlAdapter : WebControlAdapter
    {
        protected override void OnInit(EventArgs e)
        {
            if (this.Control is Button)
            {
                ((Button)this.Control).Text = "Test Adapter";
            }

            base.OnInit(e);
        }
    }
}

The problem that I see with this is that adapters cannot be stacked, so this would override any other adapter that might otherwise apply to this control.

Any ideas on better ways to solve this problem? Note that, while it would work, I consider actually adding an Init event handler in the Page for all of the controls in the markup to be excessive and want a more general solution.

A: 

Slightly more than you're after, but perhaps PostSharp would be interesting for you. You could potentially hook onto this event with it.

Noon Silk
I need to be able to intercept OnInit on in-box controls, not just controls that I have the source code for. So I don't think this will help me much.
binarycoder