Introduction
In this article, I am going to explain how to play a YouTube video in ASP.NET web application using AJAX Modal Popup. While working with any web application in any technology, be it ASP.NET, or PHP, or Java, or any other language, sometimes it’s necessary to play a media file or any media online on your web page based on the client’s requirement. Recently, a few days ago, I got a new requirement from my client to play a YouTube video on the webpage.
Actually, they wanted one textbox and one button with the name Play Video on the webpage. When a user enters the URL of the YouTube video in the given textbox and clicks on the button, one Modal Popup window will open and load the video from YouTube to play that video in a popup window.
Implementation
First, we need to register the AJAX Window Toolkit with our web application.
- <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
Now, we will write the HTML code with one textbox and one button, as following.
For, opening the popup window and playing the video, you need to write the following JavaScript code.
- <script type="text/javascript">
- function ShowModalPopup() {
- var url = $get("<%=txtUrl.ClientID %>").value;
- url = url.split('v=')[1];
- $get("video").src = "//www.youtube.com/embed/" + url
- $find("mpe").show();
- return false;
- }
- function HideModalPopup() {
- $get("video").src = "";
- $find("mpe").hide();
- return false;
- }
- </script>
Actually, when a user clicks on Play Video button, this JavaScript function will be called and will open a popup window that fetches the video from YouTube based on the entered video URL. Now, when the user clicks on the close button in popup function of JavaScript, the “HideModelPopup” function will be called and the Modal Popup will close.
Output Screen
After you click the Play Video button, the Modal Popup will open and show/play the YouTube video.
Conclusion
In this write-up, I explained how to play YouTube videos on the web page using AJAX Control Toolkit. I hope this article helps the beginner developers to build a better application.