5

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

3
  • 1
    can you post some of the source or generated code? without it this is very hard to diagnose. Commented May 19, 2010 at 10:03
  • sure, I just tend to avoid doing so as there's quite a lot of it, I'll try and cut it down a bit Commented May 19, 2010 at 10:38
  • You've stated that you have lots of code, and so it's not in the code-behind... So where is it? In the aspx? In an external js file? Loaded from a database/xml file and read by the code behind? Commented May 31, 2010 at 2:53

5 Answers 5

11
+75

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.

Sign up to request clarification or add additional context in comments.

8 Comments

maintainability drops to zero though if I do this: we're talking about 200 lines of JS that does a lot of stuff, most of which using control clientIDs to do it. that kind of code is very difficult to maintain when it's in the backend...
You need to refactor your scripts then. This is the correct way of doing this. Sorry.
i.e., you will have to rewrite you scripts so that they can be placed in js files. Then you will have to call ScriptManager.RegisterClientScriptBlock and ScriptManager.RegisterStartupScript as needed. There's no way you are going to get what you are trying to do to work without calls to the ScriptManager. Scripts in ascx/aspx isn't good practice anyway and doesn't help performance.
Christ, sorry for posting an answer. Post the answer then.
So sorry to waste your time. Can you post your answer?
|
5

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.

4 Comments

Yeah, that unfortunately only works if the code is present on the original page in the first place. As I'm using dynamic controls and loading it via an UpdatePanel (i.e. via javascript) the new javascript functions are not recognised as functions!
Hmmm... I know evals are not the best thing to fall back on, but what about placing this call within the UpdatePanel callback listed above? ... //update whatever here eval(document.getElementById('Code').innerHtml); ...
might work, but that's pretty much the last thing I'd like to resort to !
This was a perfect fit for me. Nice!
3

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.

1 Comment

You need a scriptmanager to use updatepanels, and the code is all internal to the usercontrol (embedded on the page) as it uses control-specific IDs, so this is not really goign to help.
0

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.

Comments

-1

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.

4 Comments

This small example is only indicative of my process, the real code is around 200 lines of javascript that does some very complex stuff. I need to maintain it, so there's not really an option of keeping the javascript in the code behind!
In your sample you already building the Code.Text from codebehind; you're now stating you don't want to execute the javascript from codebehind?? I assumed that you'd replace the alert with the call to a new function, passing the ID as parameter or something like that, anyway - just trying to help
I understand that, however I did say that there was more to it in my original post.
One last option; perhaps enabling the viewstate of the code literal control would do something on callback?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.