2013-12-13 24 views
6

當我重定向到另一個頁面後,如何使我的JavaScript在代碼中工作?我有一個asp按鈕控件,當我點擊那個按鈕,我想要提醒,然後導航到另一個頁面。當我在我的代碼中(在JS代碼之前或之後)有一個Response.Redirect時,8次嘗試都不起作用。當我評論重定向出來時,一些(2,7 & 8)工作。帶有重定向的JavaScript警報背後的代碼

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

回答

7

你可以嘗試以下方法:

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

感謝隊友的作品! –

+0

不用擔心,很高興它幫助:) – 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); 
    }