简体   繁体   English

从ASP.net后台创建和调用JavaScript函数时,它应该是未定义的

[英]JavaScript function is supposed to be undefined when created and called from ASP.net code-behind

I want to execute a JavaScript function from code-behind, (eg as a server-side button click event) and the firing button is inside an UpdatePanel. 我想从代码后台执行JavaScript函数(例如,作为服务器端按钮单击事件),并且触发按钮位于UpdatePanel内部。 I've written two methods for it: 我为此写了两种方法:

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;
        }

When I call Redirect method, I see a 当我调用重定向方法时,我看到一个

Uncaught ReferenceError: postToPage is not defined 未捕获的ReferenceError:未定义postToPage

error in browser console. 浏览器控制台错误。

I also tested Redirect method with RegisterStartupScript but the error did not disappear. 我还使用RegisterStartupScript测试了重定向方法,但该错误并未消失。

What is wrong with my approach? 我的方法有什么问题?

我在代码中看到的一个“错误”是,在此行上,您不会在任何地方使用包含脚本的最终字符串:

string strForm = PreparePOSTForm(destinationUrl, data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM