1

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

结果变量可以具有以下三个值中的任何一个(如果服务器响应):

i) 对 ii) 错 iii) 错误

此代码的主要问题是三个 if 语句中的每一个中的新选项卡脚本都可以正常工作。但是,由于某种原因,打开 Results.aspx 页面的最后一个脚本没有执行。如果注释掉所有其他代码,该脚本编写得很好,因为它可以完美执行。我应该如何解决问题?

我尝试用 Response.Redirect("Results.aspx") 替换它,但是然后它会执行并且所有其他三个脚本都不会执行。

4

1 回答 1

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,特别是:

启动脚本由其键和类型唯一标识。具有相同键和类型的脚本被认为是重复的。页面中只能注册一个具有给定类型和密钥对的脚本。尝试注册已注册的脚本不会创建该脚本的副本。

在您的情况下,您注册的两个脚本中的类型和键都是相同的。

您可以使用密钥唯一标识它们,然后单独注册它们。但是你必须记住,执行顺序是不能保证的:

不保证脚本块按照注册的顺序输出。

于 2013-04-18T16:24:47.430 回答