Asp.net usercontrol will not run javascript inside update panel

I saw similar problems and answers, but no one seems to fix the problem.

I have a user control inside the update panel. Inside my user control, I output javascript.

javascript doesn't work when fired. If I move javascript to the parent page outside the usercontrol / update panel, it starts. This does not make sense, since I cannot use this usercontrol on another page without duplicating the code ... by duplicating all javascript (another site) or adding links to the .js file on every page that he used on (the same site) . It is less portable

I just want to output javascript using a control (inside the update panel).

The updated panel is mentioned for the accuracy of what I am doing. It does not work even if I place usercontrol outside of service packs.

Keeping simplicity (this does not work for me):

UserControl:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="_location.ascx.cs" Inherits="_location" %> <script type="text/javascript"> function test() { alert('Hello World!'); } </script> <a href="javascript:void(0);" onclick="javascript:test();"> Find For Me </a> 

PARENTS:

 <uc1:_location runat="server" ID="_location" /> 

Debugging in chrome tells me: "Untrained ReferenceError: test not defined"

If I add javascript directly to onclick, as shown below, it works:

 onclick="alert('Hello World!');" 

And as stated above, moving the function to the parent page ALSO works.

It is as if the browser is ignoring the output of the script from the user control.

Any ideas?

+6
source share
5 answers

When you have an UpdatePanel and that the UpdatePanel updates its contents, it treats it as plain text / html (not code), it has no parser to run the script and its accessibility for the page.

So this is the content,

 <script type="text/javascript"> function test() { alert('Hello World!'); } </script> <a href="javascript:void(0);" onclick="javascript:test();"> Find For Me </a> 

after the client update panel of the update panel launches and updates the content of the page, the script part is not analyzed - its plain text / html for the page.

However this part works

 <a href="javascript:void(0);" onclick="alert('Hello World!');">Find For Me</a> 

because the analysis of the onclick attribute is performed when you click on it.

The following workarounds are available:

  • Move your javascript to an external file
  • Move script outside UpdatePanel
  • Register the script in code with RegisterClientScriptBlock or alternative functions.
+5
source

Thanks to Aristos for sending me along the right path ... Although his solution worked, it did not answer the question about javascript coming out from inside usercontrol, but instead suggested moving it outside. This was not the desired result, as indicated, since it was not held inside the control for easy carrying.

Here is my solution that does the following: CS file:

 String script = "<script type=\"text/javascript\">"; script += "function test() {"; script += "alert('Hello World!');"; script += "</script>"; Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "locationScript", script); 

You can use the string constructor if the script is longer, but it works anyway.

This completely saves the code inside the usercontrol and works from the onclick event of the tag.

+1
source

In addition to the solution that Adam Wood wrote, I have to say that you should use the ScriptManager to register the script when using the update panel, at least in .net 4.0, because otherwise it will not work.

So you can enable the PageLoad event for usercontrol:

 string script = @" alert('this is a test'); alert('it worked')"; ScriptManager.RegisterStartupScript(Page,Page.GetType(),"scriptMelhoria",script,true); 
+1
source

Try it;

You can find your script elements after the udpdate panel callback and evaluate them.

Add a special attribute to your inline script tag to select items after the callback request.

 <script type="text/javascript" data-tag='myscript'> function test() { alert('Hello World!'); } </script> 

And add this script to your aspx update panel container file.

 <script> if (Sys !== undefined) { var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(endPostbackRequest); } function endPostbackRequest(sender, args) { $("script[data-tag='myscript']:not([data-run])").each( function () { eval.apply(window, [$(this).text()]); $(this).attr('data-run', '1'); }); } </script> 
0
source

The preferred way to handle javscript related to the DOM elements in UpdatePanel is to subscribe to the endRequest event and execute your code here. For example, you want to install click event handlers here.

 // that is standard way for asp.net to execute JS on page load // pretty much the same as $(function(){ ...}) with jquery function pageLoad() { // find PRM instance and subscribe to endRequest Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest); } function endRequest() { // set all handlers to DOM elements that are within UpdatePanel $('<%= myButton.ClientID %>').on('click', test) } function test(e) { alert('Hi') } 

An alternative solution would be to use event delegation as follows:

 function pageLoad() { // delegate click event on .myButton inside .container // to the .container DOM element $('.container').on('click', '.myButton', test) } 

And add a div with a class called container around the update panel. In this case, your div.container never deleted from the DOM, so all event handlers on it will be saved after partial postbacks.

The same code without jquery and using only asp.net ajax will look like this:

 function pageLoad() { Sys.UI.DomEvent.addHandler($("myContainer"), "click", delegatedTest); } function delegatedTest(e) { // since asp.net ajax does not support event delegation // you need to check target of the event to be the right button if (e.target.id == "myButton") test(e) } function test(e) { alert("HI") } 
-1
source

All Articles