jQuery $(document).ready and UpdatePanels?

后端 未结 19 1527
庸人自扰
庸人自扰 2020-11-22 01:32

I\'m using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in $(document).ready . For example:

相关标签:
19条回答
  • 2020-11-22 01:54

    User Control with jQuery Inside an UpdatePanel

    This isn't a direct answer to the question, but I did put this solution together by reading the answers that I found here, and I thought someone might find it useful.

    I was trying to use a jQuery textarea limiter inside of a User Control. This was tricky, because the User Control runs inside of an UpdatePanel, and it was losing its bindings on callback.

    If this was just a page, the answers here would have applied directly. However, User Controls do not have direct access to the head tag, nor did they have direct access to the UpdatePanel as some of the answers assume.

    I ended up putting this script block right into the top of my User Control's markup. For the initial bind, it uses $(document).ready, and then it uses prm.add_endRequest from there:

    <script type="text/javascript">
        function BindControlEvents() {
            //jQuery is wrapped in BindEvents function so it can be re-bound after each callback.
            //Your code would replace the following line:
                $('#<%= TextProtocolDrugInstructions.ClientID %>').limit('100', '#charsLeft_Instructions');            
        }
    
        //Initial bind
        $(document).ready(function () {
            BindControlEvents();
        });
    
        //Re-bind for callbacks
        var prm = Sys.WebForms.PageRequestManager.getInstance(); 
    
        prm.add_endRequest(function() { 
            BindControlEvents();
        }); 
    
    </script>
    

    So... Just thought someone might like to know that this works.

    0 讨论(0)
  • 2020-11-22 01:54

    My answer?

    function pageLoad() {
    
      $(document).ready(function(){
    

    etc.

    Worked like a charm, where a number of other solutions failed miserably.

    0 讨论(0)
  • 2020-11-22 01:57

    In response to Brian MacKay's answer:

    I inject the JavaScript into my page via the ScriptManager instead of putting it directly into the HTML of the UserControl. In my case, I need to scroll to a form that is made visible after the UpdatePanel has finished and returned. This goes in the code behind file. In my sample, I've already created the prm variable on the main content page.

    private void ShowForm(bool pShowForm) {
        //other code here...
        if (pShowForm) {
            FocusOnControl(GetFocusOnFormScript(yourControl.ClientID), yourControl.ClientID);
        }
    }
    
    private void FocusOnControl(string pScript, string pControlId) {
        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "focusControl_" + pControlId, pScript, true);
    }
    
    /// <summary>
    /// Scrolls to the form that is made visible
    /// </summary>
    /// <param name="pControlId">The ClientID of the control to focus on after the form is made visible</param>
    /// <returns></returns>
    private string GetFocusOnFormScript(string pControlId) {
        string script = @"
        function FocusOnForm() {
            var scrollToForm = $('#" + pControlId + @"').offset().top;
            $('html, body').animate({ 
                scrollTop: scrollToForm}, 
                'slow'
            );
            /* This removes the event from the PageRequestManager immediately after the desired functionality is completed so that multiple events are not added */
            prm.remove_endRequest(ScrollFocusToFormCaller);
        }
        prm.add_endRequest(ScrollFocusToFormCaller);
        function ScrollFocusToFormCaller(sender, args) {
            if (args.get_error() == undefined) {
                FocusOnForm();
            }
        }";
        return script;
    }
    
    0 讨论(0)
  • 2020-11-22 01:58
    Sys.Application.add_load(LoadHandler); //This load handler solved update panel did not bind control after partial postback
    function LoadHandler() {
            $(document).ready(function () {
            //rebind any events here for controls under update panel
            });
    }
    
    0 讨论(0)
  • 2020-11-22 02:02

    I would use one of the following approaches:

    1. Encapsulate the event binding in a function and run it every time you update the page. You can always contain the event binding to specific elements so as not to bind events multiple times to the same elements.

    2. Use the livequery plug-in, which basically performs method one for you auto-magically. Your preference may vary depending on the amount of control you want to have on the event binding.

    0 讨论(0)
  • 2020-11-22 02:03

    An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.

    What I've done to work around this is re-subscribe to the events I need after every update. I use $(document).ready() for the initial load, then use Microsoft's PageRequestManager (available if you have an update panel on your page) to re-subscribe every update.

    $(document).ready(function() {
        // bind your jQuery events here initially
    });
    
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    
    prm.add_endRequest(function() {
        // re-bind your jQuery events here
    });
    

    The PageRequestManager is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.

    If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments (sender, eventArgs) so you can see what raised the event and only re-bind if needed.

    Here is the latest version of the documentation from Microsoft: msdn.microsoft.com/.../bb383810.aspx


    A better option you may have, depending on your needs, is to use jQuery's .on(). These method are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use .delegate() or .on(), so in those cases, you're better off re-subscribing.

    0 讨论(0)
提交回复
热议问题