我遇到了同样的问题。如果在异步回发(ASP.NET 2.0、Ubuntu Server 13.10)中,“ScriptManager.RegisterStartupScript”不起作用。如果页面是第一次加载,它会很好地工作。
在浏览了
https://github.com/mono/mono/blob/master/mcs/class/System.Web.Extensions/System.Web.UI/ScriptManager.cs上的 Mono 源代码后,
我看到有一些预将脚本添加到最终输出的编译器内容:
switch (scriptEntry.ScriptType) {
case RegisteredScriptType.ClientScriptBlock:
if (scriptEntry.AddScriptTags)
WriteCallbackOutput(output, scriptBlock, scriptContentNoTags, scriptEntry.Script);
else
WriteCallbackOutput(output, scriptBlock, scriptContentWithTags, SerializeScriptBlock(scriptEntry));
break;
#if NET_3_5
case RegisteredScriptType.ClientStartupScript:
if (scriptEntry.AddScriptTags)
WriteCallbackOutput (output, scriptStartupBlock, scriptContentNoTags, scriptEntry.Script);
else
WriteCallbackOutput (output, scriptStartupBlock, scriptContentWithTags, SerializeScriptBlock (scriptEntry));
break;
#endif
case RegisteredScriptType.ClientScriptInclude:
WriteCallbackOutput(output, scriptBlock, scriptPath, scriptEntry.Url);
break;
case RegisteredScriptType.OnSubmitStatement:
WriteCallbackOutput(output, onSubmit, null, scriptEntry.Script);
break;
}
也许有人忘记定义“NET_3_5”,所以这部分不起作用。此外,在初始页面加载时,“ScriptManager.RegisterStartupScript”实际上调用了“ClientScript.RegisterStartupScript”(这就是它在这种情况下工作的原因)。
我的解决方案是使用“ScriptManager.RegisterClientScriptBlock”模拟行为(按预期工作):
/// <summary>
/// Always adds script tags.
/// </summary>
public static void ScriptManagerRegisterStartupScript(Control control, Type type, string key, string script){
if (!ScriptManager.GetCurrent(control.Page).IsInAsyncPostBack)
control.Page.ClientScript.RegisterStartupScript(type, key, script, true);
else {
string hName = String.Format("h{0}", Guid.NewGuid().ToString("N")); // Lazy way to get a unique name
ScriptManager.RegisterClientScriptBlock(control, type, key,
"function " + hName + " () {" +
"Sys.WebForms.PageRequestManager.getInstance().remove_pageLoaded(" + hName + ");" +
script + // This is why we do not support "addScriptTags==false"
"}" +
"Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(" + hName + ");",
true);
}
}