Saturday, April 26, 2008

Accessing Controls on the Master Page

The other day, a colleague of mine had a problem where he needed to disable a control on the master page. The page that he was working on was fairly big, as far as the amount of data is concerned. There were buttons on the master page that let the user manipulate the content page. The problem was that master page got rendering way before the content page and if the user clicked on the button to control the content page, ASP.NET got ticked off and threw some kind of ViewState exception.

The solution that I proposed was to disable the button until the content page gets rendered and have the content page enable the button on the master page using javascript. Since the button was on the master page, we had to do the following

1. Added a method that will find any control recursively. We “borrowed” this code from the Coding Horror site here
2. Add a public variable that was the actual id of the control we were trying to access. ASP.NET assigns a unique id to each control and needed to make sure we get the exact id
3. Used javascript after the data was done rendering to get the element by id and enabled it

Content page looked like this

public string btnName;
protected void Page_Load(object sender, EventArgs e) {
Control o = FindControlRecursive(this.Master, "Button1");
btnName = o.UniqueID;
}


And the javascript looks like this


var lnk = document.getElementById("<%= btnName %>");
alert("enabling the button");
lnk.disabled = false;


You can download the solution here

0 comments: