2013-04-18 20 views
1

我在C#下面的代碼:C# - 頁面重定向不能正常工作

if (function.Equals("Larger50")) 
{ 
     Request req = new Request(); 
     string result = req.doRequest("function=" + function + "&num=" + number, "http://localhost:4000/Handler.ashx"); 

     if (result.Equals("True") || result.Equals("true")) 
     { 
      Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/Larger.aspx?num=" + number + "', '_newtab')", true); 
     } 

     if(result.Equals("False") || result.Equals("false")) 
     { 
      Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/Smaller.aspx', '_newtab')", true); 
     } 

     if(result.Equals("Error") || result.Equals("error")) 
     { 
      Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/ErrorPage.htm', '_newtab')", true); 
     } 

     Session["result"] = result; 
     Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.location.href = 'Results.aspx'", true); 
} 

結果變量可以有以下三種中的任何值(如果服務器響應):

我)真的 ii)錯誤 iii)錯誤

此代碼的主要問題在於三個if語句中的每一箇中的新選項卡腳本正常工作。但是,打開Results.aspx頁面的最後一個腳本由於某種原因沒有執行。如果所有其他代碼都被註釋掉,那麼腳本編寫得非常完美。我應該如何解決這個問題?

我試着用Response.Redirect(「Results.aspx」)替換它,然後這個exeuctes和所有其他三個腳本永遠不會執行。

+0

將完整的網址添加到Results.aspx – saj

+0

Results.aspx是我工作的當前項目中的一個頁面。所有其他URL都是到服務器機器上的。 – Matthew

+0

這些腳本完全可以自行完成,但是當它們組合在一起時,它們不能以某種原因或另一種方式工作。這就像第一個遇到的腳本執行一樣,並且下一個腳本被忽略。 – Matthew

回答

1

應立即將所有註冊這些,而不是兩個單獨的語句:

if (function.Equals("Larger50")) 
{ 
     Request req = new Request(); 
     string result = req.doRequest("function=" + function + "&num=" + number, "http://localhost:4000/Handler.ashx"); 

     string scriptVal = ""; 

     if (result.Equals("True") || result.Equals("true")) 
     { 
      scriptVal = "window.open('http://localhost:4000/Larger.aspx?num=" + number + "', '_newtab');"; 
     } 

     if(result.Equals("False") || result.Equals("false")) 
     { 
      scriptVal = "window.open('http://localhost:4000/Smaller.aspx', '_newtab');"; 
     } 

     if(result.Equals("Error") || result.Equals("error")) 
     { 
      scriptVal = "window.open('http://localhost:4000/ErrorPage.htm', '_newtab');"; 
     } 

     Session["result"] = result; 

     scriptVal += "window.location.href = 'Results.aspx';"; 

     Page.ClientScript.RegisterStartupScript(Page.GetType(), null, scriptVal, true); 
} 

參見ClientScriptManager.RegisterStartupScript的文檔,具體是:

啓動腳本都是通過其鍵標識和它的類型。 具有相同鍵和類型的腳本被認爲是重複的。只有一個 具有給定類型和密鑰對的腳本可以在頁面中註冊。 試圖註冊已註冊的腳本不會 創建腳本的副本。

對於您的情況,類型和關鍵字在您註冊的兩個腳本中都是相同的。

您可以用一個鍵唯一標識它們,然後單獨註冊它們。但你要記住,執行的順序是不能保證:

塊不保證該腳本將在他們 被註冊的順序輸出。

+0

非常感謝你:)它工作完美:)謝謝:) – Matthew

+0

@Matthew很高興我能幫忙! – jadarnel27

+0

@ jadarne27再次感謝:) – Matthew