How to call jQuery code only before the ASP.NET postback

My colleague has got into a tricky situation where the requirement was to call the specific lines of jQuery code only before the postback. "PostBack is the name given to the process of submitting an ASP.NET page to the server for processing .". Once there is a postback (on click of button) that particular code should never ever get called again. Well, the situation is tricky but no so difficult. All he needs to do is to find out the postback occurrence using jQuery.

So the solution is that using isPostBack on the server side, register a hidden field in the page. And in the jQuery code, create object of the hidden field and check whether it is null or not. It will be null initially because it is not created yet. After the postback happens the hidden field gets created so next time the object will not be null. To register hidden field from ASP.NET code behind, you can use ClientScript.RegisterHiddenField.This method registers a hidden field in the page.

protected void Page_Load(object sender, EventArgs e)
   if (IsPostBack)
        ClientScript.RegisterHiddenField("hdnPostBack", "1");

Below jQuery code, first creates a object named "isPostBackOccured" of "hdnPostBack" hidden field. So when the page is running for the first time, it doesn't find the hidden field as it is not registered yet. So it will be null and you will see alert ("Page is called first Time"). But when the postback happens (using button click, or drop down change), the above code registers hidden field. So after the postback, the "isPostBackOccured" object will no longer be null and you will see an alert box with the message "Page is called after Postback".

$(document).ready(function () {
    var isPostBackOccured = document.getElementById('hdnPostBack');
    if (isPostBackOccured== null) alert('Page is called first Time');
    else alert('Page is called after Postback');

Note: Just for the demo, I have kept these alerts but you should put your actual jQuery code.

Sweet and Simple.....

Feel free to contact me for any help related to jQuery, I will gladly help you.