Asp.net 赢得比赛';t启动以动态添加控件

Asp.net 赢得比赛';t启动以动态添加控件,asp.net,vb.net,Asp.net,Vb.net,我正在根据服务器文件夹中显示的视频数量,动态地将htmlvideo控件添加到我的web表单中。这部分很好用。所有视频都会显示并可以播放。我在我的代码中添加了“onended”事件作为属性和函数,但该事件不会触发。我知道,由于这些控件是在添加之后添加的,所以我必须添加一个侦听器,但我不知道如何添加 这是添加控件的代码 Dim SavePath As String = "e:\ftproot\images\TechNet\" Dim Directory As New Director

我正在根据服务器文件夹中显示的视频数量,动态地将htmlvideo控件添加到我的web表单中。这部分很好用。所有视频都会显示并可以播放。我在我的代码中添加了“onended”事件作为属性和函数,但该事件不会触发。我知道,由于这些控件是在添加之后添加的,所以我必须添加一个侦听器,但我不知道如何添加

这是添加控件的代码

    Dim SavePath As String = "e:\ftproot\images\TechNet\"
    Dim Directory As New DirectoryInfo(SavePath)
    Dim allFiles As IO.FileInfo() = Directory.GetFiles("*.mov")
    Dim VidCtr As Integer = 1
    For Each singlefile In allFiles
        Dim myVid As New HtmlVideo
        myVid.Src = "https://www.rawauto.com/images/TechNet/" & singlefile.Name
        myVid.Attributes.Add("height", 140)
        myVid.Attributes.Add("runat", "server")
        myVid.Attributes.Add("type", "video/mp4")
        myVid.Attributes.Add("controls", "controls")
        myVid.Attributes.Add("onended", "VidPlayed")
        myVid.Attributes.Add("id", "Vid" & VidCtr)
        Panel1.Controls.Add(myVid)

        Dim myLbl As New Label
        myLbl.Text = Replace(UCase(singlefile.Name), ".MOV", "")
        myLbl.Width = 250
        myLbl.CssClass = "VidStyle"
        myLbl.Font.Name = "calabri"
        myLbl.Font.Bold = True
        LPanel.Controls.Add(myLbl)
    Next
这是用户看完视频后,我试图启动的功能:

Protected Sub VidPlayed(sender As Object, e As EventArgs)
    Dim Tech As New SqlConnection("server=RAW-OTT; Initial Catalog=TechNet; Integrated Security=True;")
    Dim vid As HtmlVideo = sender
    Dim vidurl As String = vid.Src
    VidName = Replace(vidurl, "https://www.rawauto.com/images/TechNet/", "")
    If Len(VidName) > 50 Then
        VidName = Mid(VidName, 1, 50)
    End If
    Dim SqlStr As String = "Select * From TechTube Where Video = '" & VidName & "'"
    Dim ttA As New SqlDataAdapter(SqlStr, Tech)
    Dim ttT As New DataTable
    ttA.Fill(ttT)
    If ttT.Rows.Count = 0 Then
        SqlStr = "Insert Into TechTube Values ('" & VidName & "', 1, 0)"
        Dim tCmd As New SqlCommand(SqlStr, Tech)
        Tech.Open()
        tCmd.ExecuteNonQuery()
        Tech.Close()
    Else
        SqlStr = "Update TechTube Set Hits = Hits + 1 Where Video = '" & VidName & "'"
        Dim tCmd As New SqlCommand(SqlStr, Tech)
        Tech.Open()
        tCmd.ExecuteNonQuery()
        Tech.Close()
    End If
    RateLabel.Visible = True
    RatingBox.Visible = True
End Sub

这是任何动态控件的旧ViewState问题,与视频无关

请记住,每次回发都会从头开始重建整个页面,包括动态控件。如果在回发(包括所有服务器事件)后仍希望看到这些控件,则必须将它们重新添加到页面中。此外,如果希望在此回发期间为控件触发事件,则需要还原控件的ViewState,并且要还原ViewState,必须在运行page_Load事件之前将控件添加回重建的页面。Page_Init或Page_PreInit可以很好地实现这一点

最后,考虑这里的性能含义。你真的想在每次用户交互时重建整个页面吗?或者,也许是时候学习使用javascript来处理这些事情了,也许是一个web api,它只需要接收一个javascript请求,而不会在你的服务器和用户的浏览器上造成整个页面循环

这只是许多其他问题和答案中的一小部分:


其他人注意:我完全回答了这个问题,而不是投票以重复的形式结束,因此我将来会有一个更好的地方作为重复问题使用。