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?
Asked
Active
Viewed 6,309 times
5 Answers
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
-
1Hmmm, 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