0

我創建了一個包含AjaxControlToolkit的AutoCompleteExtender的UserControl。當我在同一頁面上有一個或多個靜態設計的實例時,它可以很好地工作。但是,如果其中一個控件是動態添加的(例如,在UpdatePanel中),那麼該控件的<script>塊(我目前已經嵌入到源視圖中)似乎不可用(JavaScript抱怨它不能找到我連接到OnClientItemSelected的函數)。註冊OnClientItemSelected用於動態AutoCompleteExtender

我懷疑我需要在其PreRender事件中註冊UserControl的腳本,所以即使它動態地添加到頁面時它們也可用。我正在使用ToolkitScriptManager,並想象我需要從我的控件中調用ScriptManager.RegisterScriptControl(this);,然後實現IScriptControl接口。

這是正確的做法嗎?如果是這樣,要正確實現IScriptControl,是否必須將腳本塊從源視圖移到它自己的.js文件中?這將迫使我重新設計我的JS功能,因爲它調用了行內代碼來檢索ClientID的該特定實例中的子控件:

var hiddenField = $get('<%=this.hfItemID.ClientID%>');

腳本管理和JS不是我的專長,所以我想在我開始以編程方式開始添加它們之前,確保這是正確的方向,然後纔會使用戶控件複雜化,這很好。

更新

我感動的JavaScript代碼到後面,我註冊爲一個ClientScript,在希望它會讓我有點接近的地方,我需要是:

string searchScript = "function " + this.aceItemSearch.ClientID + "_getByID(sender, e) { var hfield = $get('" + this.hfItemID.ClientID + "'); if (typeof hfield === 'undefined') return; var item = eval('(' + e._value + ')'); hfield.value = item.ID; if (typeof document != 'undefined') { var control = $get('" + this.btnSearch.ClientID + "'); } control.click(); }";  
Page.ClientScript.RegisterStartupScript(this.GetType(), aceItemSearch.ClientID + "_getByID", searchScript, true); 

這適用於靜態放置的控件,但與以前一樣,不適用於動態添加的控件。該腳本不會將其放入源視圖中。

回答

0

移動腳本代碼中的靜態,的RegisterStartupScript的5參數版本被稱爲落後時的作品。提供UserControl本身作爲第一個參數:

string searchScript = "function " + this.aceItemSearch.ClientID + "_getByID(sender, e) { var hfield = $get('" + this.hfItemID.ClientID + "'); if (typeof hfield === 'undefined') return; var item = eval('(' + e._value + ')'); hfield.value = item.ID; if (typeof document != 'undefined') { var control = $get('" + this.btnSearch.ClientID + "'); } control.click(); }";  
ScriptManager.RegisterStartupScript(this, this.GetType(), aceItemSearch.ClientID + "_getItemByID", searchScript, true);