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?
You can check the IsPostBack property. Eg:
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
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
}
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.
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.
$("a[href^='javascript:__doPostBack']").click(function () {
// do something
});
精彩评论