How to call jQuery code only before the ASP.NET postback
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 asp.net 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.