C# - 以编程方式在浏览器中打开弹出窗口

时间:2013-04-18 14:49:47

标签: c# tabs popup window

我有以下代码:

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

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

                Session["result"] = result;
                Response.Redirect("Results.aspx");
            }

此代码向服务器发出请求,如果结果为true,则应创建新选项卡,并将当前窗口重定向到Results.aspx。

如果结果为false,则只应重定向到Results.aspx。

此代码的主要问题是,即使结果为true,也永远不会创建新选项卡。但是,如果我注释掉除新选项卡代码之外的所有代码,则会创建新选项卡。

为什么会这样?我该如何纠正?

2 个答案:

答案 0 :(得分:2)

问题似乎是您在脚本执行之前重定向。我也会尝试在脚本中进行重定向,所以像这样;

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

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

    Session["result"] = result;

    Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.location.href = 'http://localhost:4000/Redirect.aspx.aspx'", true);
}

答案 1 :(得分:0)

结果不一定与您正在测试的内容相匹配。

String.Equals()可能并不总是与给定字符串匹配,因为有时如果字符串已被实现,则引用可能不匹配。

我建议切换到使用String.Compare()或更好但只使用等于运算符:==

所以:

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

或者更好:

if (Convert.ToBoolean(result))
{
    Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/Transaction_Number.aspx', '_newtab')", true);
}

MSDN有一些关于如何有效比较字符串的具体指导原则:

http://msdn.microsoft.com/en-gb/library/vstudio/cc165449.aspx