wsamon
wsamon

Reputation: 41

Javascript Function Inside Dynamically Added User Control Inside Update Panel Is Not Defined

I've got an ASP.NET Webforms page that is largely dynamically generated based on information received from a database. The controls get injected into an UpdatePanel. For the most part everything is working, except one control contains a javascript function that is executed when the user clicks a button inside the control. The control works perfectly on a test page, but when used inside this dynamically created page, clicking the button returns a JS console error saying that the function "is not defined" even though a page source inspection through the browser shows that it is present. Trying to execute the function through the chrome developer tools console after that control is injected onto the page gives the same error. How do I make the function available to execute?

At a high level / pseudocode it looks like the below:

<Page>
...
     <DynamicWizardControl>
          <UpdatePanel>
               <!--dyanamically injected stuff-->
               <WizardDocumentSubmissionControl>
                    <DocumentSubmissionControl ID="Attachments" runat="server">
                         <asp:Textbox ID='txtFile' runat='server'></asp:Textbox>
                         <asp:Button ID='btnAdd' runat='server' Text='Add File' />
                         <script>
                              function submitFile<%=btnAdd.ClientID%>() {
                                   alert($('#<%=txtFile.ClientID%>').val());
                              }
                         </script>
                    </DocumentSubmissionControl>
               </WizardDocumentSubmissionControl>
               <!--End Dynamically Injected Stuff-->
          </UpdatePanel>
     </DynamicWizardControl>
</Page>

Code Behind for the WizardDocumentSubmissionControl

Page_Load
Attachments.JSSubmitButton.OnClientClick = Attachments.SubmitFileJSFunctionName

Code Behind for the DocumentSubmissionControl

Public ReadOnly Property SubmitFileJSFunctionName As String
    Get
        Return "submitFile" & btnAdd.ClientID
    End Get
End Property
Public ReadOnly Property JSSubmitButton As Button
    Get
        Return btnAddJS
    End Get
End Property

Upvotes: 0

Views: 214

Answers (1)

wsamon
wsamon

Reputation: 41

So it seems like the dynamically injected control doesn't register the javascript to the DOM. I got it to work by using the ScriptManager.RegisterClientScriptBlock to register the entire javascript function which is something I was hoping to avoid because I feel that the JS should live inside the HTML portion of the control, not the code behind. If anyone knows of any better method, please let me know.

Upvotes: 1

Related Questions