2013-12-13 29 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');の前にスラッシュが必要です。 "Request.ApplicationPath +" /anotherpage.aspx ";"); – 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); 
    } 
関連する問題