使用Code Behind实现JavaScript警告并重定向页面

7
我如何让后台JavaScript在重定向到另一页后继续工作?我有一个asp按钮控件,当我点击该按钮时,我希望弹出警告,然后导航到另一页。 当我的代码中有Response.Redirect(在JS代码之前或之后),8次尝试中没有一次有效。 当我注释掉重定向代码时,其中几个(2,7和8)有效。
//Try one
ScriptManager.RegisterStartupScript(this, GetType(), "test", "alert('test1');", true);

//Try two
ClientScript.RegisterClientScriptBlock(typeof(Page), "test", "test2");

//Try three
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "alertMessage()", true);

//Try four
ClientScript.RegisterStartupScript(GetType(), "CallMyFunction", "alertMessage()", true);

//Try five
ClientScript.RegisterStartupScript(GetType(), "CallMyFunction", "javascript: alertMessage(); ", true);

//Try six
ClientScript.RegisterClientScriptBlock(GetType(), "CallMyFunction", "<script>alert('test4')</script>");

//Try seven
Response.Write("<script>alert('test5');</script>");

//Try eight
string script = "alert('test6')";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "CallMyString", script, true);

response.redirect("pageUrlHere");
//With this code above, none of the js functions (alerts) work

//response.redirect("pageUrlHere");
//With this commented out, try 2, 7 and 8 work. 

JS函数:

function alertMessage() {
    alert('test3');
}
2个回答

10

您可以尝试以下方法:

ScriptManager.RegisterStartupScript(this,this.GetType(),"redirect",
"alert('test 9'); window.location='" + 
Request.ApplicationPath + "/anotherpage.aspx';",true);

没问题,很高兴能帮到你 :) - chridam
1
小改动,需要在页面名称前加上斜杠 ScriptManager.RegisterStartupScript(this,this.GetType(),"redirect", "alert('test 9'); window.location='" + Request.ApplicationPath + "/anotherpage.aspx';",true); - n00b

4
尝试这个,它会显示警报并导航。将其制作成单独的方法以便再次重用。
    public void ShowAlertAndNavigate(string msg , string destination)
    {
        string alert_redirect_Script = string.Format(@"<script type=""text/javascript"">
                                       alert('{0}');
                                        window.location.href = destination;
                                       </script>", msg);
        ClientScript.RegisterClientScriptBlock(this.GetType(), "alertredirectscript",   alert_redirect_Script, false);
    }

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