Creating an Image Slide Show Using ASP.NET Client Callbacks
By AzamSharp
Views: 5502

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!

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: How to autostart show
Name: gokhan aykan
Date: 10/1/2007 11:55:41 AM
Comment:
I tried several alternatives to start slide show automatically as the page is displayed.
But I am not succesful.
Any advice !
Thanks any how. This is a very succesful article.
I am waiting for the silverlight version.
regards
Subject: Not working for me!
Name: Ramya
Date: 10/2/2007 8:16:29 AM
Comment:
Can u help me? I can'e post the code here. Butthis is not working for me. The buttons are displayed, but when i click them, there is script error and nothing is seen
Subject: Works great
Name: veeblefetzer
Date: 10/24/2007 12:32:13 PM
Comment:
Good illustration of using client callbacks in asp.net. I had no trouble getting it to work. Did those who had trouble put pictures in the Pictures folder? There were none in the download.
Subject: RE: Works great
Name: AzamSharp
Date: 10/24/2007 2:44:36 PM
Comment:
Hi veeblefetzer,

I am glad you found it useful. I removed the pictures since they were pretty big in size.

Thanks,
Azam
Subject: :-)
Name: vmson
Date: 11/7/2007 10:54:40 PM
Comment:
Now I understand Client Callback !!!
Thank you so much !
Subject: ASP.NET
Name: pradeep
Date: 2/21/2008 2:33:08 AM
Comment:
hey its not working properly...i'm getting error in Default.aspx like "Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl)."..i dont know wat to do.....and another thing is that is it with page refresh or without page refresh..



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008