3

I need to detect a postback in the frontend so I can use it with JQuery to change a class on page load. How can I do this?

chobo
  • 31,561
  • 38
  • 123
  • 191
  • possible duplicate of [How can I check for IsPostBack in JavaScript?](http://stackoverflow.com/questions/59719/how-can-i-check-for-ispostback-in-javascript) – Abe Miessler Mar 11 '11 at 23:45

5 Answers5

8

You can check the IsPostBack property. Eg:

<script type="text/javascript">
    $(function()
    {
        var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;

        if (isPostBack)
        {
             alert("Postback");
        }
    });
</script>
Mun
  • 14,098
  • 11
  • 59
  • 83
3

Stolen from this post:

On the server side have this

if(IsPostBack)
{
   // NOTE: the following uses an overload of RegisterClientScriptBlock() 
   // that will surround our string with the needed script tags 
   ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}

On client side this

if(isPostBack) {
   // do your thing
}
Community
  • 1
  • 1
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • How do I get the ClientScript object. I typed it in but I am not getting an intellisense to add a namespace. – chobo Mar 12 '11 at 00:03
  • 1
    Hmmm, maybe try Page.ClientScript? It's part of System.Web.UI: http://msdn.microsoft.com/en-us/library/system.web.ui.page.clientscript.aspx – Abe Miessler Mar 12 '11 at 00:17
2

I put this variable inside the header tag of my asp.net web forms page.

<script type="text/javascript">
    var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>

The var contains a Boolean. The comparison can probably be shortened.

Tim
  • 1,045
  • 14
  • 23
1

Simple:

if you're using jquery it has to go after(jquery goes nuts otherwise):

    $(document).ready(function(){

    });

   var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;

Then

    function whatever(){
            if (isPostBack){
            //Whatever you want to do
            }else{
            //Whatever else you want to do
            }
    }

I'm actually using it with jquery to show a web service status box then force a postback to refresh a ListView, so when it posts back it doesn't invoke the web service or show the status box just the updated ListView data.

iuppiter
  • 315
  • 3
  • 9
0
$("a[href^='javascript:__doPostBack']").click(function () {
    // do something
});
Mishami
  • 470
  • 4
  • 4