Farshid
Farshid

Reputation: 5354

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, (e.g. as a server-side button click event) and the firing button is inside an 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

error in browser console.

I also tested Redirect method with RegisterStartupScript but the error did not disappear.

What is wrong with my approach?

Upvotes: 1

Views: 152

Answers (1)

Aristos
Aristos

Reputation: 66641

One "bug" I see on the code is that you do not use anywhere the Final String that contains the script, on this line:

string strForm = PreparePOSTForm(destinationUrl, data);

Upvotes: 1

Related Questions