如何在前端(aspx)检测回发(postback)

3

我需要在前端检测postback,以便在页面加载时使用JQuery更改类。我该怎么做?


可能是重复的问题:如何在JavaScript中检查IsPostBack? - Abe Miessler
5个回答

8
您可以检查IsPostBack属性。例如:
<script type="text/javascript">
    $(function()
    {
        var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;

        if (isPostBack)
        {
             alert("Postback");
        }
    });
</script>

3

这篇文章中获取:

在服务器端使用以下代码:

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

在客户端,这个

...

if(isPostBack) {
   // do your thing
}

我该如何获取ClientScript对象。我已经输入了它,但是没有智能感知来添加命名空间。 - chobo
1
嗯,也许可以尝试使用 Page.ClientScript?它是 System.Web.UI 的一部分:http://msdn.microsoft.com/zh-cn/library/system.web.ui.page.clientscript.aspx - Abe Miessler

2

我把这个变量放在了我的ASP.NET Web Forms页面的头部标签中。

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

变量包含布尔值。比较可能可以缩短。


1

简单:

如果你正在使用jQuery,它必须放在之后(否则jQuery会出问题):

    $(document).ready(function(){

    });

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

那么

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

实际上我是在使用jquery展示一个Web服务的状态框,然后强制进行postback来刷新ListView。因此,它在提交回来时不会调用Web服务或显示状态框,只有更新后的ListView数据。


0
$("a[href^='javascript:__doPostBack']").click(function () {
    // do something
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接