Search code examples
htmlasp.netvb.netvideo

How to change src of html5 video control from VB.NET Code behind (not C#)


Old VB.net website with VB codebehind.

All examples I found were for C# and even the one I found for VB.NET, Changing the source of a video in ASP.NET/VB.NET, gives me errors.

This is the control on the html page that will display an .mp4 if it is hardcoded as the "src":

<video width="320" height="240" controls id="videoHolder" runat="server">
  <source src="../videos/MP4s/english-country-dancing-example.mp4" type="video/mp4">
</video>

This is the codebehind that get's provided a video .mp4 name from a database query:

Dim videoHolder As Video

videoHolder.src = strVideoFile

However, the "Video" word is underlined in red("type Video is not defined") and the "videoHolder" word is underlined in green("BC42104: Variable 'videoHolder' is used before it has been assigned a value.)

(the variable strVideoFile does hold the path to the actual file correctly).

Now I thought I was pretty smart but I haven't programmed in VB.net for quite sometime I am stumped.

Please let me know if I can ask this question better. I haven't found any links beside the one I listed above.


Solution

  • Ok, as you note, hardcoding works.

    You can however do it this way:

            <asp:Button ID="Button1" runat="server" Text="Button" />
            <br />
            <br />
            <br />
            <video width="320" height="240"  
                id="videoHolder" runat="server" controls>
                <source  runat="server" id="mysource" />
            </video>
    

    So, by tagging the source as server, then our button click code can be:

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
    
        mysource.Attributes("src") = ResolveUrl("~/Content/Sample.mp4")
        mysource.Attributes("type") = "video/mp4"
    
    End Sub
    

    And thus, the effect is this:

    enter image description here

    A good number of examples actually suggest using RegisterScript in which some JavaScript code is used to set the src (by script injection of some JavaScript into the page thus setting the src).

    However, as above shows, you can do this by setting "source" as a server control (with runat="server").

    The next trick then is to NOT use Server.MapPath since that returns a server side windows full valid path name.

    The src needs a "client side" name resolution, and thus using ResolveUrl() spits out a valid client side (browser) URL.