0

我創建了一個包含按鈕的基本組合服務器控件。使用javascript ASP.NET獲取服務器控件上的子控件

<Custom:Class1 ID="testClass" ClientInstanceName="test1" runat="server"></Custom:Class1> 

我希望能夠得到使用JavaScript例如子控件:

VAR爲myButton = testClass.FindControl( '爲btnTest');

有沒有辦法做到這一點?

+0

服務器控件 - 服務器端。 Javascript - 客戶端。可能,你確定這是個好主意嗎? – JNF 2012-07-19 17:44:11

回答

1

創建一個客戶端對象來表示你的服務器端控件(JavaScript類)。將引用的集合放到客戶端對象上的子控件上。然後在服務器端的OnPreRender事件中創建或加載腳本來定義您的客戶端對象,同時將引用的集合傳遞給它的構造函數。

的如何嵌入包含客戶機側對象定義的JavaScript文件

實施例(把這個somwhere命名空間聲明以上:所述WebResouce(的OnPreRender如何註冊

[assembly: WebResource("myNS.stuff.clientSideObj.js", "application/x-javascript")] 
namespace myNS.stuff 
{ 

例):

ClientScriptManager cs = this.Page.ClientScript;// Get a ClientScriptManager reference from the Page class. 
Type csType = this.GetType();// Get the type from this class. 

//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource". 
String resourceName1 = "myNS.stuff.clientSideObj.js"; 
cs.RegisterClientScriptResource(csType, resourceName1); 

創建腳本以聲明客戶端對象(OnPreRender)的實例的示例:

String childControlIDsList= getChildControlList();//I am not writing this one.. just look up javascript arrays. 
String uniqueScriptKey = "myKey"; 
StringBuilder theScript = new StringBuilder(); 
theScript.AppendLine("var myObj = new clientSideObj(" + childControlIDsList + ");"); 
theScript.AppendLine("window['myClientControl'] = myObj;") //create a client side reference to your control. 
cs.RegisterStartupScript(csType, uniqueScriptKey, theScript.ToString(), true); 

我將離開客戶端對象定義給你...希望幫助!

0

如果你使用.NET 4.0,您可以設置的「ClientIDMode」財產上的按鈕Static然後使用jQuery設置ID屬性類似ID =「myButton的」和訪問它,象這樣

$("#myButton") 

如果你不使用jquery你可以,如果你多次使用控制的形式,你可以用你的自定義控件ID前綴鍵ID使用

document.getElementById("myButton") 

。請記住將自定義控件的ClientIDMode屬性也設置爲靜態。

<asp:Button ID="<%=Me.Id%>_myButton " ClientIDMode="Static" runat="server"/> 

不能完全確定這甚至是很好的做法,或者如果它可以工作,但你可以試試。(記得設置你的自定義控件ID