我有一个带有MasterPage的简单测试应用程序,一个Default.aspx页面,其中包含一个带有少量html和asp控件的UpdatePanel。
我的目的是创建动态控件和绑定事件。
我知道有关控件和绑定事件处理程序的ID的问题,因为您需要向脚本管理器注册asynccontrol。
我尝试了很多东西,但我动态创建的链接按钮在PostBack中,在MasterPage on_load中,但从不在我附加的点击事件中。
额外信息:声明性asp按钮在Default.aspx Page_Load触发其click事件并执行回发后,动态创建的LinkButton也会在Default Page_Load中启动,但从不触发btnTest_Click2。此应用程序在.NET 4.5(Visual Studio 2015)上。
有什么想法吗?
THX。
Default.aspx:
<%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestUpdatePanel._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h1>This will never change !</h1>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button runat="server" ID="btnTest" CssClass="btn btn-success" OnClick="btnTest_Click" Text="Hit me hard !" />
<div runat="server" id="testDiv">
<p>Hello this a test</p>
</div>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
</asp:Content>
Default.aspx.vb代码隐藏:
Public Class _Default
Inherits Page
Dim currentsm As ScriptManager
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
currentsm = CType(Page.Master.FindControl("sm1"), ScriptManager)
If Not IsPostBack Then
MsgBox("It's not a postback", MsgBoxStyle.DefaultButton1)
Else
MsgBox("It's a Postback !", MsgBoxStyle.DefaultButton1)
End If
End Sub
Protected Sub btnTest_Click(sender As Object, e As EventArgs)
BuildButton()
End Sub
Private Sub BuildButton()
Dim link = New LinkButton
link.ID = "linkTest"
link.ClientIDMode = ClientIDMode.Static
link.Text = "This is a new Ajax link :-)"
AddHandler link.Click, AddressOf btnTest_Click2
Dim trigger As AsyncPostBackTrigger = New AsyncPostBackTrigger
trigger.ControlID = link.ClientID
trigger.EventName = "Click"
UpdatePanel1.Triggers.Add(trigger)
currentsm.RegisterAsyncPostBackControl(link)
testDiv.Controls.Add(link)
UpdatePanel1.Update()
End Sub
Private Sub BuildDiv()
Dim divToCreate = New HtmlGenericControl
divToCreate.TagName = "div"
divToCreate.ID = "newDiv"
divToCreate.ClientIDMode = ClientIDMode.Static
divToCreate.Attributes("class") = ("btn btn-alert")
divToCreate.InnerText = "It works !"
testDiv.Controls.Add(divToCreate)
UpdatePanel1.Update()
End Sub
Protected Sub btnTest_Click2(sender As Object, e As EventArgs)
BuildDiv()
End Sub
答案 0 :(得分:0)
我终于通过使用OnInit事件来实现动态创建的控件,如下所示:
Protected Overrides Sub OnInit(e As EventArgs)
MyBase.OnInit(e)
If IsPostBack Then
currentsm = CType(Page.Master.FindControl("sm1"), ScriptManager)
Dim sender = Request.Form("__EVENTTARGET").ToString
If sender.Contains("btnTest") Then
BuildButton()
ElseIf sender.Contains("linkTest") Then
BuildDiv()
End If
End If
End Sub