开发者

When to use PreRender over PageLoad?

Related question: Get All Web Controls of a Specific Type on a Page

In the question above I asked how I can get all controls, works like a charm but something just doesn't quite fit so I thought it might be me. I have the follow开发者_高级运维ing code but it's not manipulating the controls on the page but in my theory it should work.

List<DropDownList> allControls = new List<DropDownList>();
ControlEnhancer.GetControlList<DropDownList>(Page.Controls, allControls);

foreach (DropDownList childControl in allControls)
        {
            foreach (ListItem li in childControl.Items)
            {
                li.Attributes.Add("title", li.Text);
            }

            childControl.Attributes.Add("onmouseover", "this.title=this.options[this.selectedIndex].title");
        }

Thats the code, GetControlList() code you can get from the related question which shows how it gets all controls, its just my manipulation. I am trying to get all dropdownlist listitems and add a title to them so I can have a tooltip.

It's a quick fix for IE8 and below which cuts of long text in drop down boxes.


Page_Load happens often too soon; Page_PreRender is the last moment before the page's HTML is actually rendered for the browser and in many cases is the best place to set attributes on user controls.

This because during the web form (page) life cycle there are other events in the page (and in the user controls contained in the page...) which sometimes remove/replace/overwrite (really) those attributes so the only way you can get those attributes to the browser is to append them after all other life cycle events have been fired and handled, in the Page_PreRender.


Actually, even PreRender might be too early in some cases (e.g. you could have DropDownList controls added to the control tree during databinding of controls that use DataSourceID).

There are two further events that might be more appropriate:

  • PreRenderComplete. At this point, all controls are created and the page is ready to render.

  • SaveStateComplete. Occurs after view state and control state have been saved. Any changes you make here won't be persisted to view state.

In your example (adding client-side attributes), I'd use the SaveStateComplete event to avoid unnecessary view state bloat.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜