Creating a YouTube application with ASP.NET MVC and the YouTube API

YouTube has become the main video hosting site on the internet. Not only can individuals and companies post videos but they can find numerous videos posted by other users. These videos may be very useful in helping to teach kids, employees or others specials lessons or skills. The problem is making it easy for users to view these videos without all of the other suggested videos and garbage on the YouTube site itself. Creating an application to manage the videos that you want users to see without all the other stuff is pretty straight forward.

There are two main parts to creating a YouTube player application. The first is the controller action to parse an entire YouTube video URL to pull out the unique video ID which is used by the YouTube API to display the video. This is done by simply finding the value after the video key of “v=”. This can be done using the following C# code.

var v = CompleteYouTubeURL.IndexOf("v=");
var amp = CompleteYouTubeURL.IndexOf("&", v);
string vid;
// if the video id is the last value in the url
if (amp == -1){
     vid = CompleteYouTubeURL.Substring(v + 2);
// if there are other parameters after the video id in the url
} else {
     vid = CompleteYouTubeURL.Substring(v + 2, amp - (v + 2));
ViewBag.VideoID = vid;

This will give us simply the id of the video passed in via the copied YouTube Url. We can then save this variable to the database to be used in the next step which is displaying the video in our site using the YouTube API.

On the video display view add an empty div with an id of “player” in the desired location of the video display. Then add the following link to the YouTube API followed by the configuration script block.

<script src=""></script>

  // create youtube player
  var player;
  var h = '@ViewBag.height';
  var w = '@ViewBag.width';
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      height: 360,
      width: 640,
      modestbranding: 1,
      videoId: '@ViewBag.VideoID',
      playerVars: {
        rel: 0,
        autoplay: 0,
        disablekb: 0,
        showsearch: 0,
        showinfo: 0,
        controls: 1,
        fs: 1,
        hd: 1,
        html5: 1,
        iv_load_policy: 3
      events: {
        onReady: onPlayerReady,
        onStateChange: onPlayerStateChange
  // autoplay video
  function onPlayerReady(event) {;
  // when video ends
  function onPlayerStateChange(event) {
    if( === 0) {
      //do something on end;

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *