从ASP.net代码隐藏创建和调用时,JavaScript函数应该是未定义的

时间:2014-08-31 09:58:44

标签: javascript asp.net post updatepanel code-behind

我想从代码隐藏中执行JavaScript函数(例如,作为服务器端按钮单击事件),并且触发按钮位于UpdatePanel内。我已经写了两种方法:

public static void Redirect(UpdatePanel updatePanelOrThis, string destinationUrl,
                                   NameValueCollection data)
        {
            string strForm = PreparePOSTForm(destinationUrl, data);
            ScriptManager.RegisterClientScriptBlock(updatePanelOrThis, updatePanelOrThis.GetType(), "redirectscript",
                        "<script language='javascript' type='text/javascript'> postToPage();</script>", false);
        }
        private static String PreparePOSTForm(string url, NameValueCollection data)
        {
            string jscriptString = "<script language=" + "\"" + "javascript" + "\"" + " type=" + "\"" + "text/javascript" + "\"" + ">" +
            "function postToPage() " + "{" + "var form = document.createElement(" + "\"" + "form" + "\"" + ");" +
            "form.setAttribute(" + "\"" + "method" + "\"" + ", " + "\"" + "POST" + "\"" + ");" +
            "form.setAttribute(" + "\"" + "action" + "\"" + ", " + "\"" + url + "\"" + ");" +
            "form.setAttribute(" + "\"" + "target" + "\"" + ", " + "\"" + "_self" + "\"" + ");";

            int counter = 0;
            foreach (string key in data)
            {
                jscriptString += "var hiddenField" + counter.ToString() + " = document.createElement(" + "\"" + "input" + "\"" + ");" +
            "hiddenField" + counter.ToString() + ".setAttribute(" + "\"" + "name" + "\"" + ", " + "\"" + key + "\"" + ");" +
            "hiddenField" + counter.ToString() + ".setAttribute(" + "\"" + "value" + "\"" + ", " + "\"" + data[key] + "\"" + ");" +
            "form.appendChild(hiddenField" + counter.ToString() + ");";
                counter++;
            }

            jscriptString += "document.body.appendChild(form);form.submit();document.body.removeChild(form);}</script>";
            return jscriptString;
        }

当我调用Redirect方法时,我看到了

  

未捕获的ReferenceError:未定义postToPage

浏览器控制台中出现

错误。

我还使用RegisterStartupScript测试了重定向方法,但错误并未消失。

我的做法出了什么问题?

1 个答案:

答案 0 :(得分:1)

我在代码中看到的一个“错误”是你不在任何地方使用包含脚本的Final String,在这一行:

string strForm = PreparePOSTForm(destinationUrl, data);