Chr*_*ris 33 c# asp.net ajax updatepanel scriptmanager
我有我认为应该是一个相当简单的问题,但对于我的生活,我看不出我的问题.问题与ScriptManager.RegisterStartupScript有关,这是我之前多次使用过的.
我的场景是我有一个插入页面的自定义Web控件.控件(以及一个或两个其他)嵌套在UpdatePanel中.它们被插入到PlaceHolder的页面上:
<asp:UpdatePanel ID="pnlAjax" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="placeholder" runat="server">
</asp:PlaceHolder>
...
protected override void OnInit(EventArgs e){
placeholder.Controls.Add(Factory.CreateControl());
base.OnInit(e);
}
Run Code Online (Sandbox Code Playgroud)
这是页面上唯一的更新面板.
控件需要运行一些初始的javascript才能正常工作.控制电话:
ScriptManager.RegisterStartupScript(this, GetType(),
Guid.NewGuid().ToString(), script, true);
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
Guid.NewGuid().ToString(), script, true);
Run Code Online (Sandbox Code Playgroud)
问题是脚本在首次显示页面时正确运行,但在部分回发后不会重新运行.我尝试过以下方法:
我唯一没有尝试的是使用UpdatePanel本身作为控件和类型,因为我不相信控件应该知道更新面板(并且在任何情况下似乎都没有获得更新的好方法面板?).
任何人都可以看到我在上面做错了什么吗?
谢谢 :)
好吧,回答上面的查询 - 它看起来好像占位符以某种方式混淆了ScriptManager.RegisterStartupScript.
当我将控件拉出占位符并将其直接编码到页面上时,Register脚本正常工作(我也将控件本身用作参数).
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), script, true);
任何人都可以解释为什么注入控件到PlaceHolder会阻止ScriptManager正确注册脚本?我猜这可能与动态控件的生命周期有关,但如果有一个正确的上述过程,我会欣赏(据我所知).
dc2*_*009 34
我在用户控件中使用它有一个问题(在一个页面中这很好); Button1在里面updatepanel,而在scriptmanager它上面usercontrol.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Run Code Online (Sandbox Code Playgroud)
现在看来你必须小心前两个参数,他们需要引用你的页面,而不是你的控件
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
Run Code Online (Sandbox Code Playgroud)
Zha*_*uid 15
我认为你应该使用RegisterStartupScript 的Control重载.
我在服务器控件中尝试了以下代码:
[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
protected override void OnInit(EventArgs e){
base.OnInit(e);
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的页面中我有:
protected override void OnInit(EventArgs e){
base.OnInit(e);
Placeholder1.Controls.Add(new AlertControl());
}
Run Code Online (Sandbox Code Playgroud)
Whereholder1是更新面板中的占位符.占位符还包含其他几个控件,包括按钮.
这完全符合您的预期,每次加载页面或导致更新面板更新时,我都会收到一条警告"Hello".
您可以看到的另一件事是挂钩在更新面板请求期间触发的一些页面生命周期事件:
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(EndRequestHandler);
Run Code Online (Sandbox Code Playgroud)
该PageRequestManager endRequestHandler事件触发每一个更新面板完成其更新时间-这将让你调用一个方法来建立你的控制.
我唯一的问题是:
Kel*_*tex 10
当您调用ScriptManager.RegisterStartupScript时,"Control"参数必须是将更新的UpdatePanel中的控件.您需要将其更改为:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
Run Code Online (Sandbox Code Playgroud)