Learn ASP.NET Web Forms and ASP.NET MVC. Intensive courses for professional developers. Conducted by Bipin Joshi in Thane. Read more details here.
Untitled 1

Creating Slide Show using ASP.NET AJAX

Introduction

Companies often need a mechanism to showcase their products in the form of a web based slide show. Of course you can use plain JavaScript to develop such slide show but ASP.NET AJAX makes your life easy. In this article we will develop a simple slide show with the help of page methods and client script extensions. The slide show can be started and paused by the end user and keeps looping through the images. User can also navigate the images manually.

Creating SlideShow class

To begin developing the slide show create a new AJAX enabled web site. Add a new java script file named JScript.js. We will create a class called SlideShow that will do all the job of playing, pausing and navigating the slide show. The SlideShow class is developed using ASP.NET AJAX client script extensions and looks as shown below:

Type.registerNamespace("Demo");

Demo.SlideShow=function()
{
    this._slides=new Array();
    this._delay=2000;
    this._currentIndex=0;
    this._pause=false;
}

Demo.SlideShow.prototype=
{
    get_Slides:function()
    {
        return this._slides;
    },
    
    set_Slides:function(value)
    {
        this._slides=value;
    },
    
    get_Delay:function()
    {
        return this._delay;
    },
    
    set_Delay:function(value)
    {
        this._delay=value;
    },
    
    get_CurrentIndex:function()
    {
        return this._currentIndex;
    },
    
    set_CurrentIndex:function(value)
    {
        if(value<0)
        {
            this._currentIndex=this._slides.length-1;
            return;
        }
        if(value>=this._slides.length)
        {
            this._currentIndex=0;
        }
        else
        {
            this._currentIndex=value;
        }
    },
    
    get_IsPaused:function()
    {
        return this._pause;
    },
    
    set_IsPaused:function(value)
    {
        this.pause=value;
    },
    
    Pause:function()
    {
        this._pause=true;
    },
    
    Play:function()
    {
        this._pause=false;
        window.setTimeout("slideshow.ShowImage()",
	this.get_Delay());
    },
    
    ShowFirst:function()
    {
        this._currentIndex=0;
        this.ShowImage();
    },
    
    ShowLast:function()
    {
        this._currentIndex=this._slides.length-1;
        this.ShowImage();
    },
    
    ShowNext:function()
    {
        var newIndex=this._currentIndex +1;
        this.set_CurrentIndex(newIndex);
        this.ShowImage();
    },
    
    ShowPrevious:function()
    {
        var newIndex=this._currentIndex -1;
        this.set_CurrentIndex(newIndex);
        this.ShowImage();
    },
    
    ShowImage:function()
    {
        var img=$get("Image1");
	if(img.style.visibility=="hidden") 
	{ 
	img.style.visibility="visible"; 
	} 
        var slides=this.get_Slides();
        var curIndex=this.get_CurrentIndex();
        img.src=slides[curIndex];
        if(this.get_IsPaused()==false)
        {
            this.set_CurrentIndex(curIndex+1);
            this.Play();
        }
    }
}


Demo.SlideShow.registerClass("Demo.SlideShow");

var slideshow=new Demo.SlideShow();

The code begins by registering a new namespace called Demo. It then creates a class called SlideShow. The constructor of the SlideShow class declares four member variables. The _slides variable points to an array that contains URLs of the slide images. The _delay variable indicates the time between two slides in milliseconds. The _currentIndex variable holds index of the current slide from the _slides array. Finally, the _pause variable indicates if the slide show has been paused (true) or running (false).

The prototype of SlideShow class defines four properties in terms of getter and setter methods namely Slides, Delay, CurrentIndex and IsPaused. All the properties except set_CurrentIndex() need no explanation. The set_CurrentIndex() property checks the supplied value. If the value is falling outside the bounds of slides array then it adjusts it either to 0 or (length of array -1) depending on the condition. This is essential so that the slide show can keep on repeating itself endlessly.

The Pause() method simply sets the _pause member variable to true. Doing so causes the slide show to pause.

The Play() method starts the slide show. It first sets _pause variable to false and then invokes setTimeout() method of window java script object. The setTimeout() method accepts two parameters - the code to be executed after certain delay and time span in milliseconds after which the code is to be executed. In our case the delay comes from get_Delay() property. The setTimeout() method is scheduled to call ShowImage() method.

The ShowImage() method performs the core job of displaying an image. It refers CurrentIndex and Slides properties. It then sets src property of the image tag to appropriate image from Slides array. Note that Image1 is the ID of an image tag that we will be adding later. Also note the use of $get() method that is equivalent to document.getElementById() method. The CurrentIndex is then incremented and Play() method is called again. This way an endless loop is formed and the slide show runs contineously.

ShowFirst(), ShowLast(), ShowNext() and ShowPrevious() methods simply adjust the _currentIndex member variable appropriately and call ShowImage() method to display a slide.

After the class is created it is registered with AJAX framework using registerClass() method. Finally, a global variable of SlideShow class is declared.

Creating a Web Form

Open the default web form in Visual Studio IDE. Ensure that it contains a ScriptManager control. Add an HTML table with two rows and one column. Add a <img> tag in the first row and six HTML button controls in the second row. The following figure shows the layout of the web form.

Set the value properties of the six buttons as shown in the above figure.

Now select the ScriptManager control and set its EnablePageMethods property to true. Also, add the JScript.js file into its Scripts collection (see below).

Creating a web method that returns image URLs

The SlideShow class allows you to specify slides using Slides property. One way to use Slides property is to assign a fixed array of image URLs. However, more appropriate approach is to get the image URLs on the fly from the server. This way you can return images based on some condition or even a database driven logic. This calls for creating a web method that returns an array of image URLs. This web method will then be called from the client side java script.

Go in the web form code behind and add the following web method.

[WebMethod]
public static string[] GetSlides()
{
string[] slides = new string[4];
slides[0] = "images/slide1.jpg";
slides[1] = "images/slide2.jpg";
slides[2] = "images/slide3.jpg";
slides[3] = "images/slide4.jpg";
return slides;
}

The GetSlides() is a static method and is marked with [WebMethod] attribute. It returns an array of strings containing image URLs. In our example we are hard coding the image URLs but they can easily come from database or any other data store.

Calling the GetSlides() web method from java script

Now that we are ready with GetSlides() web method we need to call it from the client side java script. Switch to the HTML source view and add the following <script> block in the <HEAD> section of the web form.

<script type="text/javascript">
function pageLoad()
{
var img=$get("Image1"); 
img.style.visibility="hidden"; 
PageMethods.GetSlides(OnSuccess,OnError,OnTimeOut);
}
        
function OnSuccess(result)
{
slideshow.set_Slides(result);
slideshow.set_Delay(2000);
slideshow.Play();
}
        
function OnError(result)
{
alert(result.get_message());
}

function OnTimeOut(result)
{
alert(result);
}
</script>

The <script> block contains pageLoad() function that is called automatically by AJAX framework whenever a web form is loaded on the client side. It is like server side Page_Load event of ASP.NET. The pageLoad() method hides the image. This is done to avoid displaying the broken image marker by the browser. The pageLoad() function then invokes GetSlides() web method with the help of PageMethods inbuilt class. In ASP.NET AJAX all execution is asynchronous and hence GetSlides() method accepts callback functions that will be called after successful execution, erroneous execution and timeout conditions respectively.

The OnSuccess() function receives the string array returned by GetSlides() web method and sets Slides property of SlideShow class accordingly. It then sets delay of the slide show to 2000 milliseconds. Finally it calls Play() method of SlideShow class to start the slide show.

The OnError() and OnTimeOut() methods simply display respective error messages.

Next, modify the markup of HTML button controls as shown below:

<input id="Button1" ... onclick="slideshow.ShowFirst()" />
<input id="Button2" ... onclick="slideshow.ShowPrevious()" />
<input id="Button5" ... onclick="slideshow.Pause()"/>
<input id="Button6" ... onclick="slideshow.Play()"/>
<input id="Button3" ... onclick="slideshow.ShowNext()" />
<input id="Button4" ... onclick="slideshow.ShowLast()"/>

As you can see the onclick event of the buttons simply calls respective methods of the SlideShow class.

That's it! Run the web form and you should see our slide show playing in the browser.

 

 


Bipin Joshi is the founder of BinaryIntellect Consulting and conducts professional training programs on ASP.NET in Thane. He is a published author and has authored or co-authored books for Apress and Wrox press. To know more about him click here. To know more about his training programs go here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Associated Links
Download Source Code

Tags : ASP.NET AJAX Web Forms
Posted On : 27 May 2007
Current Rating :
Rate this article :


This page is protected by copyright laws. Copying in any form is strictly prohibited. For Copyright notice and legal terms of use click here.

Protected by Copyscape