Jun 292012
 

While working with jQuery one of the methods that I’ve found that I use a lot is $(document).ready(). The biggest problem that I’ve run into with using this method is that when working within ASP.NET and doing an AJAX postback this event does not fire automatically. For good reason, but it can cause serious problems when I need that event to fire on partial postbacks as well.

For those of you unfamiliar the document ready event only fires when the page is doing a full load and is done loading. When doing an AJAX postback you are only doing a partial load of the page, thus the appeal, but the document the ready event will not fire.

This can cause problems with your page if inside your document ready function you make modifications or attach events to controls that are impacted or inside of the AJAX update panel. When an AJAX postback happens any events or properties that have been changed on controls inside the updatepanel will be lost. So the simplest solution is to fire your document ready event again so that the changes can be remade automatically.

It is fairly simple to do this as there is an easy method to tell if you are currently inside of an AJAX postback. Inside of the script manager manager class there is a property that tells if you are inside of an Async postback, similar to Page.IsPostBack property. To fire the document ready function on load of the page when inside of an AJAX postback you would use code like below.

if (this.Page.IsPostBack && ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
      ScriptManager.RegisterStartupScript(this, this.GetType(), "document_Ready", "document_Ready();", true);

Then the corresponding JavaScript code to do your client side work.

$(document).ready(document_Ready);

function document_Ready() {
}

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.