Rectangle 27 2

You'll want to respond to these events that the upload panel will invoke before and after a partial postback.

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(...);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(...);

How to insert this in the code, should I call a method when update panel loads

You'll want to setup these events anytime before the partial postback is invoked. In the past I've added calls to wire up these handlers on the button click that is invoking the partial postback. You could also add it to your document.load code.

how to call a javascript fn in Update panel on Partial postback in asp...

javascript asp.net
Rectangle 27 2

You'll want to respond to these events that the upload panel will invoke before and after a partial postback.

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(...);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(...);

How to insert this in the code, should I call a method when update panel loads

You'll want to setup these events anytime before the partial postback is invoked. In the past I've added calls to wire up these handlers on the button click that is invoking the partial postback. You could also add it to your document.load code.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

how to call a javascript fn in Update panel on Partial postback in asp...

javascript asp.net
Rectangle 27 1

When you do a partial postback that updates particular html elements, those elements are recreated and therefore lose their javascript event bindings. The startup script recreates those bindings.

So every time I will have to provide a new key to the script as the old one is already registered?

I believe the key only has to be unique across a single postback. If I'm correct, you would only need each script you want to register to have a unique key, you wouldn't need to generate a random string or anything like that.

c# - Understanding RegisterStartupScript and postbacks - Stack Overflo...

c# jquery asp.net registerstartupscript
Rectangle 27 1

If you don't want your control to refresh on every UpdatePanel's postback - set UpdateMode for the UpdatePanel that hosts your control to Conditional this way it will be refreshed only when its own trigger or child control fire (Ref: http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.updatemode(v=vs.90).aspx).

That said, you don't have to manually add pageLoaded event handler on client side. Use intristic pageLoad function which fires on every page load be it via UpdatePanel or otherwise (Ref: http://msdn.microsoft.com/en-us/library/bb386417(v=vs.90).aspx)

One other way to fire a JS function is from server-side code. Every time your control loads or performs some server-side init - use ClientScript.RegisterStartupscript call to make sure JS function will be called on the client afterward, for example

ClientScript.RegisterStartupscript(this.GetType(),"myFunc", "myFunction();", true);

javascript - Call a function after every updatepanels partial postback...

javascript jquery asp.net updatepanel
Rectangle 27 1

If you don't want your control to refresh on every UpdatePanel's postback - set UpdateMode for the UpdatePanel that hosts your control to Conditional this way it will be refreshed only when its own trigger or child control fire (Ref: http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.updatemode(v=vs.90).aspx).

That said, you don't have to manually add pageLoaded event handler on client side. Use intristic pageLoad function which fires on every page load be it via UpdatePanel or otherwise (Ref: http://msdn.microsoft.com/en-us/library/bb386417(v=vs.90).aspx)

One other way to fire a JS function is from server-side code. Every time your control loads or performs some server-side init - use ClientScript.RegisterStartupscript call to make sure JS function will be called on the client afterward, for example

ClientScript.RegisterStartupscript(this.GetType(),"myFunc", "myFunction();", true);

javascript - Call a function after every updatepanels partial postback...

javascript jquery asp.net updatepanel
Rectangle 27 10

You can either tap into the PageRequestManager endRequestEvent:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});

Or if it is control events you're trying to attach, you can use jQuery live events.

Another option is to do the event delegation manually. It is what the "live" event are doing under the covers. Attach the event handler to the document itself, then conditionally execute your method if the sender of the event was element you expect.

$(document).click(function(e){  
    if($(e.target).is(".collapseButton")){  
        $(this).find(".collapsePanel").slideToggle(500);  
    }  
})

thanks that worked, guess it is not as effecient but its only for this one page.

It is actually very efficient. If you have event handlers on every row of a grid, this will have only one event handler for the entire grid. It gets even better if you have several event handlers for each row. You can get by with only one....and nothing to attach to new records created manually or via partial postbacks.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - jquery needs to rebind events on partial page postback - ...

javascript jquery binding postback
Rectangle 27 10

You can either tap into the PageRequestManager endRequestEvent:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});

Or if it is control events you're trying to attach, you can use jQuery live events.

Another option is to do the event delegation manually. It is what the "live" event are doing under the covers. Attach the event handler to the document itself, then conditionally execute your method if the sender of the event was element you expect.

$(document).click(function(e){  
    if($(e.target).is(".collapseButton")){  
        $(this).find(".collapsePanel").slideToggle(500);  
    }  
})

thanks that worked, guess it is not as effecient but its only for this one page.

It is actually very efficient. If you have event handlers on every row of a grid, this will have only one event handler for the entire grid. It gets even better if you have several event handlers for each row. You can get by with only one....and nothing to attach to new records created manually or via partial postbacks.

javascript - jquery needs to rebind events on partial page postback - ...

javascript jquery binding postback
Rectangle 27 1

Ok, after creating my own test website and tinkering around, here's what I got to work:

<%@ Control Language="C#" 
            AutoEventWireup="true" 
            CodeFile="TestControl2.ascx.cs" 
            Inherits="Controls_TestControl2" %>

This is Test Control 2
<%@ Page Language="C#" 
         MasterPageFile="~/Site.master" 
         AutoEventWireup="true" 
         CodeFile="10049777.aspx.cs" 
         Inherits="_10049777" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server" />
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" 
        UpdateMode="Conditional" 
        ChildrenAsTriggers="true">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server"
                Text="Partial postback" 
                OnClick="Button1_Click" />
            <br /><br />
            <asp:Panel runat="server" ID="Panel1" />
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var TestControl1 = LoadControl("Controls\\TestControl1.ascx");

        Panel1.Controls.Add(TestControl1);
        ScriptManager.RegisterStartupScript(TestControl1, 
                                            TestControl1.GetType(), 
                                            "TestControl1Script", 
                                            "alert(\"control 1\");", 
                                            true);
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    var TestControl2 = LoadControl("Controls\\TestControl2.ascx");

    Panel1.Controls.Clear();
    Panel1.Controls.Add(TestControl2);

    ScriptManager.RegisterStartupScript(TestControl2, 
                                        TestControl2.GetType(), 
                                        "TestControl2Script", 
                                        "alert(\"control 2\");", 
                                        true);
}

That does appear to work. However the crux of the matter is still unclear to me,as too why the javascript when inside the user control doesnt't run, or when a different user control is loaded async, the request manager still sees the original controls javascript.

Also, this way works great in this test with some easy javascript, but in reality, I will have 50+ lines of code that I would rather not shove into a string variable, as I lose all debugging and maintainability. Thanks for the time though, I have been slamming my head againsnt the wall trying to figure it out.

I think it's due to how ASP.NET handles controls that are added dynamically to the UpdatePanel. This question shows more insight into this issue that may be helpful to you.

I hear ya on the debugging/maintainability. In my opinion, and how I would handle this is how I personally do my own JavaScript/jQuery. I have one script.js that contains all of my code and depending on what page I'm on, that page's init() fires binding everything I need. It's a spin-off of Paul Irish's Markup Based Unobtrusive Comprehensive Dom Ready Execution post.

@MikeKiemen If you wouldn't mind upvoting this since you did find it useful enough to implement into your edited question. Upvotes aren't just for finished correct answers, but for useful answers and rewarding those for the time they spent on your question. I did spend a couple hours between the 2 answers I posted. It would be much appreciated. =D

asp.net - Javascript in a user control doesnt fire when partial postba...

asp.net user-controls updatepanel partial-postback
Rectangle 27 1

Ok, after creating my own test website and tinkering around, here's what I got to work:

<%@ Control Language="C#" 
            AutoEventWireup="true" 
            CodeFile="TestControl2.ascx.cs" 
            Inherits="Controls_TestControl2" %>

This is Test Control 2
<%@ Page Language="C#" 
         MasterPageFile="~/Site.master" 
         AutoEventWireup="true" 
         CodeFile="10049777.aspx.cs" 
         Inherits="_10049777" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server" />
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" 
        UpdateMode="Conditional" 
        ChildrenAsTriggers="true">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server"
                Text="Partial postback" 
                OnClick="Button1_Click" />
            <br /><br />
            <asp:Panel runat="server" ID="Panel1" />
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var TestControl1 = LoadControl("Controls\\TestControl1.ascx");

        Panel1.Controls.Add(TestControl1);
        ScriptManager.RegisterStartupScript(TestControl1, 
                                            TestControl1.GetType(), 
                                            "TestControl1Script", 
                                            "alert(\"control 1\");", 
                                            true);
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    var TestControl2 = LoadControl("Controls\\TestControl2.ascx");

    Panel1.Controls.Clear();
    Panel1.Controls.Add(TestControl2);

    ScriptManager.RegisterStartupScript(TestControl2, 
                                        TestControl2.GetType(), 
                                        "TestControl2Script", 
                                        "alert(\"control 2\");", 
                                        true);
}

That does appear to work. However the crux of the matter is still unclear to me,as too why the javascript when inside the user control doesnt't run, or when a different user control is loaded async, the request manager still sees the original controls javascript.

Also, this way works great in this test with some easy javascript, but in reality, I will have 50+ lines of code that I would rather not shove into a string variable, as I lose all debugging and maintainability. Thanks for the time though, I have been slamming my head againsnt the wall trying to figure it out.

I think it's due to how ASP.NET handles controls that are added dynamically to the UpdatePanel. This question shows more insight into this issue that may be helpful to you.

I hear ya on the debugging/maintainability. In my opinion, and how I would handle this is how I personally do my own JavaScript/jQuery. I have one script.js that contains all of my code and depending on what page I'm on, that page's init() fires binding everything I need. It's a spin-off of Paul Irish's Markup Based Unobtrusive Comprehensive Dom Ready Execution post.

@MikeKiemen If you wouldn't mind upvoting this since you did find it useful enough to implement into your edited question. Upvotes aren't just for finished correct answers, but for useful answers and rewarding those for the time they spent on your question. I did spend a couple hours between the 2 answers I posted. It would be much appreciated. =D

asp.net - Javascript in a user control doesnt fire when partial postba...

asp.net user-controls updatepanel partial-postback
Rectangle 27 1

Another method you could take is using jQuery's .on() method.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

So, for example, you could wrap your UserControls with a div using the same class like so:

<div class="userControl">
    <span>This is UserControl 2</span>
</div>

Then, in your MasterPage, at the very bottom before your </body> tag, you include your jQuery reference and your jQuery script. In my example, I print out the contents of the <span /> inside of the UserControl when the <span /> is clicked.

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
    <script>
        $("div[id$=UpdatePanel1]")
            .on("click", "div.userControl span", function() { 
                alert($(this).html().trim()); 
            });
    </script>
</body>
</html>

asp.net - Javascript in a user control doesnt fire when partial postba...

asp.net user-controls updatepanel partial-postback
Rectangle 27 1

Another method you could take is using jQuery's .on() method.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

So, for example, you could wrap your UserControls with a div using the same class like so:

<div class="userControl">
    <span>This is UserControl 2</span>
</div>

Then, in your MasterPage, at the very bottom before your </body> tag, you include your jQuery reference and your jQuery script. In my example, I print out the contents of the <span /> inside of the UserControl when the <span /> is clicked.

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
    <script>
        $("div[id$=UpdatePanel1]")
            .on("click", "div.userControl span", function() { 
                alert($(this).html().trim()); 
            });
    </script>
</body>
</html>

asp.net - Javascript in a user control doesnt fire when partial postba...

asp.net user-controls updatepanel partial-postback
Rectangle 27 6

I'm guessing from 'partial page postback' you're working in Asp.net land.

Sys.Application.add_load(function() { });

You should still be able to use all the normal jQuery stuff inside that func.

Exactly. That's exactly why MS invented that load event: they knew they'd be blowing away DOM elements after partial postbacks, and they needed to give devs a single way to do stuff when the page is ready, regardless of whether fancy AJAX UpdatePanels are used or not.

Perfect. This did the trick. Just called my same setup methods directly and via this event and it now works perfectly. Cheers!

javascript - jquery needs to rebind events on partial page postback - ...

javascript jquery binding postback
Rectangle 27 6

I'm guessing from 'partial page postback' you're working in Asp.net land.

Sys.Application.add_load(function() { });

You should still be able to use all the normal jQuery stuff inside that func.

Exactly. That's exactly why MS invented that load event: they knew they'd be blowing away DOM elements after partial postbacks, and they needed to give devs a single way to do stuff when the page is ready, regardless of whether fancy AJAX UpdatePanels are used or not.

Perfect. This did the trick. Just called my same setup methods directly and via this event and it now works perfectly. Cheers!

javascript - jquery needs to rebind events on partial page postback - ...

javascript jquery binding postback
Rectangle 27 2

Check out the "live" feature of jQuery 1.3 here. You can add events to future elements as well as current elements on the page. This may simplify the code you'll need to write.

we are not using 1.3 so cnt' use live.

We use "live" events a lot, but sometimes they don't meet out needs. If you're using jQuery to manipulate the DOM, you'll need to re-manipulate it after it's been updated via the partial postback.

You can achieve the same effect of live by doing the event delegation manually.

how can I do this manually?

javascript - jquery needs to rebind events on partial page postback - ...

javascript jquery binding postback
Rectangle 27 2

Check out the "live" feature of jQuery 1.3 here. You can add events to future elements as well as current elements on the page. This may simplify the code you'll need to write.

we are not using 1.3 so cnt' use live.

We use "live" events a lot, but sometimes they don't meet out needs. If you're using jQuery to manipulate the DOM, you'll need to re-manipulate it after it's been updated via the partial postback.

You can achieve the same effect of live by doing the event delegation manually.

how can I do this manually?

javascript - jquery needs to rebind events on partial page postback - ...

javascript jquery binding postback
Rectangle 27 0

function pageLoad(sender, args) {

  InitialiseSettings();
}

function InitialiseSettings(){
    // replace your DOM Loaded settings here. 
    // If you already have document.ready event, 
    // just take the function part and replace here. 
    // Not with document.ready 
    $(element).slideUp(1000, method, callback});

    $(element).slideUp({
                   duration: 1000, 
                   easing: method, 
                   complete: callback});
}

or try with add_endRequest event handler:

Better do it once move the all the code from document.ready to InitialiseSettings function and pass it to pageLoaded event

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitialiseSettings)

Thanks a lot, but to initialization easing in InitialiseSettings .

$(document).ready(function () {Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InitialiseSettings)  function InitialiseSettings() {             //easing, other initialization goes here         }  })  </script>

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

asp.net - Execute javascript after a partial postback of an updatepane...

javascript asp.net
Rectangle 27 0

The most elegant solution (using jQuery 2.x) is this:

Use the "on" event. Make sure you bind the event to the document and not to the element itself!

$(document).on('click', 'div.messages', function () {
    console.log('click on div.messages');
    return false;
});

javascript - jquery needs to rebind events on partial page postback - ...

javascript jquery binding postback
Rectangle 27 0

Found a good explanation for the inline script issue

In short: partial postbacks updates the innerHtml of the update panel, thus it sees the blob of html as straight text and thus doesnt register any script tags within the html.

Each control has a its own javascript file with a function named similar to

function controlNameLoad() { ..do your stuff }

Inside the content panel code (inside a case statement to determine which control to load)

dim ctrl = LoadControl("UCName.ascx")
panel.Controls.Add(ctrl)
ScriptManager.RegisterClientScriptInclude(ctrl, ctrl.GetType(), "UserJS", "UCName.js")
ScriptManager.RegisterStartupScript(ctrl, ctrl.GetType(), "UserJS", "controlNameLoad()", True)

asp.net - Javascript in a user control doesnt fire when partial postba...

asp.net user-controls updatepanel partial-postback
Rectangle 27 0

Some DOM elements are replaced when you do a partial postback, and of course, the new elements will loose jQuery bindings. You can use the ScriptManager class to register a script that will be executed after the partial postback finishes (have a look here)

javascript - jquery needs to rebind events on partial page postback - ...

javascript jquery binding postback
Rectangle 27 0

When you do a partial postback that updates particular html elements, those elements are recreated and therefore lose their javascript event bindings. The startup script recreates those bindings.

So every time I will have to provide a new key to the script as the old one is already registered?

I believe the key only has to be unique across a single postback. If I'm correct, you would only need each script you want to register to have a unique key, you wouldn't need to generate a random string or anything like that.

c# - Understanding RegisterStartupScript and postbacks - Stack Overflo...

c# jquery asp.net registerstartupscript