简体   繁体   中英

JavaScript code inside UpdatePanel

Ok: I've got an UpdatePanel on an aspx page that contains a single Placeholder.

Inside this placeholder I'm appending one of a selection of usercontrols depending on certain external conditions (this is a configuration page).

In each of these usercontrols there is a bindUcEvents() javascript function that binds the various jQuery and javascript events to buttons and validators inside the usercontrol.

The issue I'm having is that the usercontrol's javascript is not being recognised. Normally, javascript inside an updatepanel is executed when the updatepanel posts back, however none of this code can be found by the page (I've tried running the function manually via firebug's console, but it tells me it cannot find the function).

Does anyone have any suggestions?

Cheers, Ed.

EDIT:

cut down (but functional) example:

Markup:

<script src="/js/jquery-1.3.2.min.js"></script>
  <form id="form1" runat="server">
    <div>

    <asp:ScriptManager ID="Script" runat="server" />

    <asp:Button ID="Postback" runat="server" Text="Populate" OnClick="PopulatePlaceholder" />

    <asp:UpdatePanel ID="UpdateMe" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Postback" EventName="Click" />
    </Triggers>
        <ContentTemplate>
            <asp:Literal ID="Code" runat="server" />
            <asp:PlaceHolder ID="PlaceMe" runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>
    </div>
 </form>

C#:

protected void PopulatePlaceholder(object sender, EventArgs e)
{
    Button button = new Button();
    button.ID = "Push";
    button.Text = "push";
    button.OnClientClick = "javascript:return false;";
    Code.Text = "<script type=\"text/javascript\"> function bindEvents() { $('#" + button.ClientID + "').click(function() { alert('hello'); }); }  bindEvents(); </script>";
    PlaceMe.Controls.Add(button);
}

You'll see that the button does not poput the alert message, even though the code is present on the page.

EDIT2:

Ok, just to make it clear, the production code is significantly more complex than just a single function bound onto a literal, and contains a large number of

<%= Control.ClientID %>

bits of code that'll be very difficult to factor off into non-specific functions, and pointless as they're each only used in one place (we're talking very specific validation and the odd popout trigger + some logic).

Get rid of that Literal control and use the ScriptManager to register your script. What you are doing doesn't work for the same reason

window.document.getElementById('someId').innerHtml = "<script type=\"text/javascript\">alert('hey');</script>";

doesn't work. Try this:

protected void PopulatePlaceholder(object sender, EventArgs e)
{
    Button button = new Button();
    button.ID = "Push";

    button.Text = "push";
    button.OnClientClick = "return false;";


    string script = "function bindEvents() { $('#" + button.ClientID + "').click(function() { alert('hello'); }); }  bindEvents();";

  ScriptManager.RegisterClientScriptBlock(this.Page, typeof(SomeClass), Guid.NewGuid().ToString(), script, true);


  PlaceMe.Controls.Add(button);
} 

The parameters to RegisterClientScriptBlock may need to change, but you get the idea.

To re-run some js after an update-panel has fired I've always used this

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
    function(sender, args) {
        //update whatever here
    });

Also if you have any references to elements within the update panel you can refresh those variables within that function as well, otherwise you'll have old refs that wont work.

Add the scriptmanager (Ajax Extensions) to your page and add your scriptreferences inside that manager. The manager will load each script tags on ajax-based-pageload (and not just the initial load) - move all needed javascript code inside the updatepanel and you're pretty much done.

    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Path="../lib/jquery-1.2.6.pack.js" />

Didn't read the question good enough (and without the sample). See my new response.

Maybe you are looking for this: http://api.jquery.com/live/

Nearly .bind() compatible (exceptions listed in the link above) - but also binds to elements added/changed later on.

Or maybe give also .delegate() a try - can not directly replace .bind() calls, but is in most cases much faster.

Somehow it seems your Code.Text gets lost in translation somewhere - don't know specifics, perhaps it's by design; anyway the next does work:

    protected void PopulatePlaceholder(object sender, EventArgs e)
    {
        Button button = new Button();
        button.ID = "Push";
        button.Text = "push";
        button.OnClientClick = "javascript:return false;";
//        Code.Text = 
        PlaceMe.Controls.Add(button);
        PlaceMe.Controls.Add(new LiteralControl("<script type=\"text/javascript\"> function bindEvents() { $('#" + button.ClientID + "').click(function() { alert('hello'); }); }  bindEvents(); </script>"));
    }

Since you're already building the javascript code from codebehind you might as well add the control dynamically too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM