2010年6月9日 星期三

Asp.net Master 會更改元件id值問題

因為Master會自動更新元件id值
結果導致JavaScript的一些依造id判別的檔案全部都掛了 囧
所以就找方法

結果有大大分享這方法
試了一下 可以跑
就貼上來分享
^_^

後端的CODE

public void RenderJSArrayWithCliendIds(params Control[] wc)
{
if (wc.Length > 0)
{
StringBuilder arrClientIDValue = new StringBuilder();
StringBuilder arrServerIDValue = new StringBuilder();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Now loop through the controls and build the client and server id's
for (int i = 0; i < wc.Length; i++)
{
arrClientIDValue.Append("\"" +
wc[i].ClientID + "\",");
arrServerIDValue.Append("\"" +
wc[i].ID + "\",");
}

// Register the array of client and server id to the client
cs.RegisterArrayDeclaration("MyClientID",
arrClientIDValue.ToString().Remove(arrClientIDValue.ToString().Length - 1, 1));
cs.RegisterArrayDeclaration("MyServerID",
arrServerIDValue.ToString().Remove(arrServerIDValue.ToString().Length - 1, 1));

// Now register the method GetClientId, used to get the client id of tthe control
cs.RegisterStartupScript(this.Page.GetType(), "key",
"\nfunction GetClientId(serverId)\n{\nfor(i=0; i "\n{\nif ( MyServerID[i] == serverId )\n" +
"{\nreturn MyClientID[i];\nbreak;\n}\n}\n}", true);
}
}


前端JS的CODE

var TextBox = document.getElementById(GetClientId("txtTest"));



出處:http://www.codeproject.com/KB/scripting/Masterpage-Javascript.aspx

沒有留言:

張貼留言