开发者

How to detect a postback in frontend (aspx)

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
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜