Question

I have created a UserControl that contains the AjaxControlToolkit's AutoCompleteExtender. It works well when I have one or more statically designed instances on the same page. However, if one of these controls is added dynamically (say, within an UpdatePanel), the <script> block (which I currently have embedded in the Source view) for that one control does not seem to be available (JavaScript complains that it can't find the function I am wiring up to OnClientItemSelected).

I suspect I need to register the scripts for the UserControl in its PreRender event, so they are available even when it is added to the page dynamically. I'm using the ToolkitScriptManager, and imagine I need to call ScriptManager.RegisterScriptControl(this); from my control, and then implement the IScriptControl interface.

Is this the right approach? If so, to correctly implement IScriptControl, do I have to move the script block out of Source view and into its own .js file? That would force me to redesign my JS function, because it calls inline code to retrieve the ClientID for a subcontrol within that specific instance:

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

Script Management and JS aren't my specialty, so I want to be sure that's the right direction before I complicate a UserControl that was working great until I started adding them programatically.

Update

I've moved the javascript into code behind, and am registering it as a ClientScript, in the hopes it will get me a little closer to where I need to be:

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);

This works for the statically placed control, but as before, not for the dynamically added one. The script just doesn't make it into the Source View.

Was it helpful?

Solution

Moving the script to the code behind works when the static, 5-argument version of RegisterStartupScript is called. Provide the UserControl itself as the first parameter:

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top