views:

738

answers:

4

How to detect/track/check postback in javascript(e.g in asp.net Page.isPostBack())? Any suggestion?

A: 

You can only keep track of the postback if you are using AJAX requests or have a hidden field of some sort that the javascript reads on page load. Otherwise the page is regenerated and all POST data is lost; as you would expect and hope.

Robert Massaioli
+4  A: 

ASPX:

<input type="hidden" id="_ispostback" value="<%=Page.IsPostBack.ToString()%>" />

Client-side Script:

function isPostBack() { //function to check if page is a postback-ed one
  return document.getElementById('_ispostback') == 'True';
}

PS: I have not tested it but I've done somthing similar before and it works.

o.k.w
As a matter or preference I add runat="server" to the hidden input and change it's value in the codebehind file but this works just fine. And I would recommend jQuery to do the javascript because that would become: function isPostBack() {return $("#_ispostback").val() == 'true';}
Robert Massaioli
@Shhnap: Yes I agree. Just a lazy way out for me :P
o.k.w
Why bother inserting an `<input>` element? You could just have isPostBack() directly return the value of Page.IsPostBack: `return <%= Page.IsPostBack %>;`
RickNZ
@RickNZ: That's a pretty good idea. Post as answer, I'll up-vote it :)
o.k.w
Sure: I added it to my earlier answer.
RickNZ
There is a reason why a hidden field is better, just using a javascript function will only load this value on actual post back, but for asynch postback it will not, using an input field within a an update panel that is set to updatemode=always, will make this work even on asynch postbacks.
Shrage Smilowitz
A: 

See following:

<script type="text/javascript">

function invokeMeMaster() {

var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';

if (chkPostBack == 'false') {

alert('Only the first time');

}
}



window.onload = function() { invokeMeMaster(); };

</script>
Brij
+2  A: 

If you want to check whether the current page will be a postback if the user clicks on a submit button, you can check for the presence of ViewState:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="xxxxx" />

You can use something like document.getElementById("__VIEWSTATE") or the jQuery equivalent.

However, if you want to see whether the current page was generated in response to a postback, then you need to insert that data into the page on the server side first.

For example:

function isPostBack() {
  return <%= Page.IsPostBack %>;
}
RickNZ
There you go. +1 :)
o.k.w