Image slide shows are common in most of the web applications. In this article I will demonstrate how to create a very simple slide show using ASP.NET Client Callbacks and JavaScript.

Introduction:

 

Image slide shows are common in most of the web applications. In this article I will demonstrate how to create a very simple slide show using ASP.NET Client Callbacks and JavaScript.

 

Registering Client Callbacks:

 

The first step is to register the client callbacks for the page. This is accomplished by implementing the ICallbackEventHandler interface. The ICallbackEventHandler interface contains two methods namely GetCallbackResults and RaiseCallbackEvent. I will explain the purpose of these events later. For now let’s see the implementation of the client callbacks registration.

 

private void RegisterCallbacks()

        {

            string callbackRef = ClientScript.GetCallbackEventReference(this, "arg", "recieveServerData", "context");

            string script = String.Empty;

 

            if (!ClientScript.IsClientScriptBlockRegistered("callServer")) 

            {

                script = "function callServer(arg,context) { " + callbackRef + "}";

                ClientScript.RegisterClientScriptBlock(this.GetType(), "callServer", script, true);

            }

        }   

 

The ClientScript.GetCallbackEventReference takes four arguments. The first argument is the Page object for which we are enabling the callbacks. The second argument is any data you want to pass to the server method. The third argument is the name of the method which will be invoked once the callback is completed. And finally the forth argument is the context.

 

ClientScript.RegisterClientScriptBlock registers the “callServer” event to the page. This method is responsible for invoking the GetCallbackResults and RaiseCallbackEvent on the server side.

 

GetCallbackResults and RaiseCallbackEvent Methods:

 

Let’s take a look at the GetCallbackResults and RaiseCallbackEvent methods. RaiseCallbackEvent method is fired when the user invokes the callServer method from the client side (You can name the client JavaScript function any name. I am using “callServer” for demonstration purposes). The RaiseCallbackEvent also takes a string parameter “eventArgument” which can be any data you want to pass from the client function.

 

The GetCallbackResults is fired when the processing is completed and it return the results to the client.

 

public string GetCallbackResult()

        {

            return SlideShowHelper.GetImage(index);        

        }    

 

        public void RaiseCallbackEvent(string eventArgument)

        {

            index = Int32.Parse(eventArgument);                 

        }

 

The index is an Int32 class level variable:

 

private int index = -1;

 

The purpose of the index is to get the correct image from a collection of the images. I should mention here that all the images are stored in a server side folder named “Pictures”. Now, let’s see the SlideShowHelper.GetImage method which is responsible for retrieving the image from the array of images.

 

Retrieving an Image from the Folder:

 

Retrieving an image from the folder is performed by the SlideShowHelper class. Take a look at the GetImage method below:

 

public static string IMAGES_FOLDER = @"Pictures/";

 

public static string GetImage(int index)

        {

            // You can cache the

            string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath(SiteConfiguration.GetImagesFolderPath()));

                      

 

            if (index > files.Length)

                return "DEC";

 

            if (index < 0)

                return "INC";

 

            return CreateImageTags(IMAGES_FOLDER,System.IO.Path.GetFileName(files[index]));           

        }

 

First, I retrieve all the files from the Pictures folder. You can cache the list of files and put a cache dependency on the Pictures folder. This way the cache will only be updated when the contents of the directory has changed. I also check that if the index is within the bounds of the files array. Finally, the call to the CreateImageTags is used to generate the image control and send it to the client.

 

private static string CreateImageTags(string folderName,string fileName)

        {

            return "<img width=\"300px\" height=\"300px\" src=\"" + folderName + fileName + "\"/>";

        }

 

Make sure that the IMAGES_FOLDER path contains the back-slash and not the forward-slash. The back-slash will work on both IE and FireFox while forward-slash will only work on IE.

 

The Client Side Code:

 

The client side code is very simple. Let’s check it out.

 

<div id="display">

   

    </div>

   

    <input type="button" value="Previous" onclick="loadPreviousImage()" />

    <input type="button" value="Stop" onclick="stopSlideShow()" />

    <input type="button" value="Play" onclick="startSlideShow()" />

    <input type="button" value="Next" onclick="loadNextImage()" />

 

In the above code I have an empty DIV element called “display” which will be populated with the generated image tag. There are couple of input buttons which are used to iterate through the images collection.

 

Now, let’s take a look at the JavaScript functions.

 

 

<script language="javascript" type="text/javascript">

 

var index = -1;

var timerId = null;

 

function stopSlideShow()

{

    window.clearInterval(timerId);

}

 

function startSlideShow()

{   

    timerId = window.setInterval(loadNextImage,2000);    

}

 

function loadPreviousImage()

{   

    index--;

    callServer(index,'');

}

 

function loadNextImage()

{   

    index++;

    callServer(index,'');    

}

 

function recieveServerData(response)

{    

    if(response == "DEC")

    index--;

   

    if(response == "INC")

    index++;

    

    if(response != "DEC" && response != "INC")

    {       

       document.getElementById("display").innerHTML = response;   

    }

}

 

</script>

 

The startSlideShow is used to start the slide show and will call loadNextImage after every 2 seconds. The stopSlideShow is used to stop the slide show and will clear the interval set by the startSlideShow method.

 

The function receiveServerData first checks that the index is within the bounds of the array. If everything went fine then it assigns the innerHTML property of the DIV element with the HTML of the image.

 

You can view the slide show in the animation at the following link:


Live Animation

 

 I hope you liked the article, happy programing!