Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there such a thing as 'if (!Page.IsPostBack)' in jQuery or javascript?

Is there a way to detect if when the page loads it is a postback or just the page loading?

like image 498
FarFigNewton Avatar asked Aug 19 '11 23:08

FarFigNewton


2 Answers

JavaScript has no concept of post back. The simplest way to detect this client-side would be to have [Insert Your Server Side Language Here] write/set a JavasScript variable on post back.

In C#, it would look a bit like this:

ClientScript.RegisterClientScriptBlock(GetType(), 
         "isPostBack", 
         String.Format("var isPostback = {0};", IsPostBack.ToString().ToLower()),
         true);

JavaScript:

if(isPostback) {
     // Postback specific logic here
}
like image 198
James Hill Avatar answered Nov 01 '22 08:11

James Hill


I use an asp:hiddenfield which gets its value on page_load.

On the client you can get the value as a string using jQuery, compare it to 'true' resulting in a boolean.

HTML:

<asp:HiddenField runat="server" ID="hdnIsPostback" />

VB.NET (in page_load):

Me.hdnIsPostback.Value = Me.IsPostBack

Javascript:

var isPostback = $("#<%=hdnIsPostback.ClientID%>").val().toLowerCase() === "true";
like image 39
Krizzz Avatar answered Nov 01 '22 07:11

Krizzz