c# - 将 LoadControl 用于其中包含 javascript 的用户控件

标签 c# javascript user-controls

这可能属于“我认为你做错了”类别,但我有一个用户控件,其中包含 javascript,我想在更新面板中动态加载它。这样一来,初始页面加载占用空间很小,但如果用户发出请求,就会加载控件(没有异常)。

我发现加载控件时我的 javascript 没有被执行。是否有一些魔法可以让 javascript 执行,或者它永远不会发生,因为浏览器不会重新解析加载的 html 标签?

我的用户控件

<div>hello</div>
<script type="text/javascript" >
alert('hello');
</script>

页面ascx

<asp:Button OnClick="LoadTheControl" runat="server">Click to Load</asp:Button>
<asp:UpdatePanel ID="myUPanel" runat="server">
    <asp:PlaceHolder ID="WantControlHere" runat="server" />
    <Triggers>
          <asp:AsyncPostBackTrigger ControlID="LoadTheControl" />
    </Triggers>
</asp:UpdatePanel>

页面优化

protected void LoadTheControl(object sender, EventArgs e)
{
    MyControl control = (MyControl)LoadControl("~/MyControl.ascx");
    control.ID = Guid.NewGuid().ToString();
    WantControlHere.Controls.Add(control);
}

Firebug 向我展示了我的控件的所有代码,但它没有执行 javascript。

请指出我的愚蠢。

最佳答案

我认为为了在加载控件后执行 javascript,您必须使用 ScriptManager.RegisterStartupScript 方法注册它。

在控件的 Page_Load 方法中注册要执行的脚本,如下所示:

ScriptManager.RegisterStartupScript(this, this.GetType(), "sub", "alert('me');", true);

关于c# - 将 LoadControl 用于其中包含 javascript 的用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7225730/

相关文章:

c# - 方法 C# 的通用抽象参数

c# - Windows 窗体 : Making a cursor bitmap partially transparent

c# - WPF 在单独的 UI 线程上加载动画? (C#)

c# - 在 WinForms 中遍历 CheckedListBox?

asp.net-mvc - ASP .NET MVC正确的UserControl体系结构

c# - 在派生的 C# 用户控件中处理 Windows 通知

javascript - 密码强度计

javascript - 无法同时从 awesomefont 更改文本和图标

javascript - 如何从外部 javascript 函数调用 typescript 函数

c# - 当我只有字符串格式的控件名称时,如何动态添加 UserControl?银光,C#