.net event model strikes again

Often times i’ve heard other programmers complain about the .net event model doing dumb things, today i ran into an issue that i believe ended up needing far too much work to get it to perform correctly. To summarize my issue, i had a single aspx page, and one of my layout user controls (the footer). The page contained a number of literals, which were toggled on and off from button click events within them. My task was to add an item to the footer (a copyright notice) that was only to appear on certain pages…so my thought was to create a label in the footer, declare that footer control on my page, and use that declaration to call a method on the footer control to toggle that label’s visiblity along with the toggling of the literals, as i saw fit. Seemed simple enough, but i was sooo wrong.

Toggle methods

[code lang="c#"] public class Footer : UserControl { protected Label streetPilot; public void showStreetPilot() { streetPilot.Visible=true; } public void hideStreetPilot() { streetPilot.Visible=false; } } [/code]

Problem: because of the fact that the page was being built with a pagetemplate class, the page was not aware of the footer on Page Load. So my instantiation of the footer control that was needed to call the method on said control would throw an error, since as far as the page was concerned, that control wasnt there yet.

Pre-Render method on the aspx page

[code lang="c#"] private void Survey_PreRender(object sender, EventArgs e) { if (CopyRight == 1) { Footer foot = this.FooterControl as Footer; foot.showStreetPilot(); } else { Footer foot = this.FooterControl as Footer; foot.hideStreetPilot(); } } [/code] Pre-render to the rescue. By instantiating the footer control in the pre-render, i had access to the toggle method i had created on the user control. Great. But now i needed something for the pre-render to check each time the page was posted or posted back, to see if it should run the show or hide method. This time, viewstate was necessary. I created a property called CopyRight

Copyright property that handles viewstate

[code lang="c#"] public int CopyRight { get { if (ViewState["copyright"] != null && ViewState["copyright"] is int) copyRight = (int) ViewState["copyright"]; return copyRight; } set { ViewState["copyright"] = value; } } [/code] Ultimately, each button click had to set the property CopyRight as either 1 to turn the line of text on, or -1 to turn it off.

What an inordinately complicated dance to change the visiblity of a single line of text. Yargh.

Much thanks to my co-worker Seth for his help with this one.



If you liked this, you should subscribe to Coworking Weekly.

You get one totally free email every Thursday full of the best coworking links I've found that week, along with coworking announcements & deals from around the world.

Sign up now, unsubscribe anytime.

23
Jun 2006
AUTHOR Alex Hillman
CATEGORY

elsewhere

COMMENTS No Comments