Something To Code

All about programming and information security

Create a video gallery with modal using ASP.NET and Bootstrap - Youtube 3

We are in the 3rd article of the series about Youtube API. The articles are:

  1. Load a single predefined video
  2. Load a custom video with the Youtube API in ASP.NET
  3. Create a video gallery with modal using ASP.NET and Bootstrap (this article)

We saw in the previous how to load a custom video from the backend using ASP.NET. For this one we will use the same approach to create our gallery, plus Bootstrap for the modal.

The player

We will need to put the player we saw on the first article in the Bootstrap modal, as it’s shown below.

<div class="modal fade" id="youtube-modal">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
				<h4 class="modal-title"></h4>
			<div class="modal-body">
				<!-- Player for Youtube API -->
				<div id="player"></div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal-dialog -->
</div><!-- /.modal -->

The Javascript

There are 2 scripts to be used. The first one is the general script, which I've shown in the previous articles and it didn't change. The second one is the script below, which will handle the video gallery.

var player;

$('#youtube-modal').on('', function (event) {
	var link = $(event.relatedTarget);
	var videoId ='video-id');
	var videoTitle ='video-title');
	var videoWidth ='video-width');
	var videoHeight ='video-height');

	var modal = $(this);

	player = new YT.Player('player', {
		height: videoHeight,
		width: videoWidth,
		videoId: videoId

$('#youtube-modal').on('', function (event) {
	$('#youtube-modal .modal-title').html('');
	$('#youtube-modal .modal-body').html('<div id="player"></div>');

The View

As you saw in the javascript above we are using only one modal. The magic happens in the code below, where I am passing all parameters via data-* attribute. I am using the same Model from the previous article.

<div class="row">
	@foreach (var item in Model)
		<div class="col-md-4">
			<a href="#" data-toggle="modal" data-target="#youtube-modal" data-video-title="@item.Title" data-video-id="@item.Id" data-video-width="@item.Width" data-video-height="@item.Height">
				<img src="" alt="@item.Id" />

As you can see there is no mystery on working with Youtube API and ASP.NET. And the next article will show how you can detect the state of the videos, which is very important for tagging and user interaction.

Check the full code here: