Categories
Looking glass
Navigate/Search

Name Mangling, Solution 2

Here is a much cleaner solution. Instead of having to modify all of your javascript calls to use a new function to get elements by partial id or name, you can put a recursive function in the Master Pages onload, which will walk through all the controls and create a javascript variable named with the controls original name, which points to the object declared by the new name. As long as you don’t use any special characters in your elements ids/names, this works like a charm.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace TestPage
{
public partial class TestPage : System.Web.UI.MasterPage
{
System.Text.StringBuilder strControls = new System.Text.StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
controlWalker(this.Page);
Page.ClientScript.RegisterStartupScript(this.GetType(), “ctrl_ids”, strControls.ToString(), true);
}
private void controlWalker(Control ctrl)
{
if (ctrl.HasControls())
{
foreach (Control ctrl2 in ctrl.Controls)
{
controlWalker(ctrl2);
}
}
else
{
string sClientId = ctrl.ClientID;
string sOriginalId = ctrl.ID;
strControls.Append(”var “);
strControls.Append(sOriginalId);
strControls.Append(”=document.getElementById(’”);
strControls.Append(sClientId);
strControls.Append(”‘);”);
}
}
}
}

One Response to “Name Mangling, Solution 2”

  1. ForrestLedbetter.com » Blog Archive » Master Page Name Mangling Says:

    [...] just read over some of my oldest posts, and found this gem. While I stand by it still, the code is unreadable, and using some class names that will not be [...]

Leave a Reply