1
我想從代碼隱藏中執行JavaScript函數(例如作爲服務器端按鈕單擊事件),並且觸發按鈕位於內部一個UpdatePanel。我已經寫了兩個方法吧:從ASP.net代碼隱藏中創建和調用JavaScript函數應該是undefined
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;
}
當我呼叫重定向的方法,我看到在瀏覽器控制檯
Uncaught ReferenceError: postToPage is not defined
錯誤。
我還測試了與RegisterStartupScript
重定向方法,但錯誤並沒有消失。
我的方法有什麼問題?
一個錯誤,我在這個代碼中看到的是在這條線'string strForm = PreparePOSTForm(destinationUrl,data);'strForm'沒有在任何地方使用 – Aristos 2014-08-31 10:07:18
謝謝@Aristos你的線索解決了這個問題 – Farshid 2014-08-31 10:12:31
然後我給它一個答案。 – Aristos 2014-08-31 10:30:42