ASP.NET MVC3 Slideshow Control Using JQuery and XML

Table of contents

Introduction

In this tutorial, I will share with everyone the steps to recreate the ASP.NET Slideshow Control with jQuery and XML using ASP.NET MVC 3. The features are still identical with the one previously created using ASP.NET, jQuery slideshow with navigation controls from Dynamic Drive and jQuery slideshow with XML. This version also allows us to have multiple instances of this control on the page, customize the width and height, options to hide or show navigation controls, specify XML file source, and other settings for each instance. I have put together a step-by-step tutorial on how I have accomplished this.

Figure 1

ASP.NET-MVC3-Slideshow.jpg

Getting Started

Shown in Figure 2 is the structure of the project. You're welcome to download the demo project. Here is the brief summary of the project.

  • The Slideshow class/module is in the Models folder
  • Slideshow partial view/user control in the Shared folder
  • XML files related to the images information in the XML folder
  • simplegallery.js file in the Scripts folder
  • Example of how to call the partial view or user control from the ASPX and Razor view engine, areas, and with or without a master page

Figure 2

ASP.NET-MVC3-Slideshow-project.png

Models

The YsaSSModel class contains the slideshow properties and the helper class YsaSSHelper is being used to generate the slideshow Div, JavaScript and ID. In ASP.NET, every time we drop a User Control onto a page, it will automatically include an ID property that uniquely identifies the control. On the other hand, in ASP.NET MVC, I don't find a way to do that except by manually assigning the complete ID to the User Control. There might be a way to accomplish that, but let's keep it simple for the time being. The WrapperID method is responsible for returning the unique ID for each User Control or partial view. The value of the ID property is the combination of the static text "ysaSlideShowDiv" and a number. If we include multiple user controls on the page, their IDs will look something like ysaSlideShowDiv1, ysaSlideShowDiv2… ysaSlideShowDivN. Since the WrapperID is generated by a static method, you will notice that it will increment every time we refresh the page. Don't worry about it because that will not break anything.

Listing 1
 

private string _wrapperID = YsaSSHelper.GetNextId();
        public string WrapperID
        {
            get
            {
                return "ysaSlideShowDiv" + _wrapperID;
            }
        }
 

Here is the list of available properties and methods associated with the slideshow control:
 
  • CreateDiv - create a placeholder for the slideshow control
  • CreateScript - generate a dynamic jQuery script
  • XMLSource - get or set the path to the XML file
  • XPath - set the elements and attributes in an XML document for navigation
  • Width - get or set the width of the slideshow
  • Height - get or set the height of the slideshow
  • AutoPlay [true, false] true = start the slideshow automatically without pressing the Play button and vice versa
  • ShowNavigation[true, false] true = show the navigation control, or false = hide the navigation control
  • Delay_btw_slide - get or set the delay between each image slide.
  • FadeDuration - get or set the fade duration between each slide.
  • Cycles_before_stopping - get or set the number of rotations before stopping the rotation. If we set 99, it will rotate 99 times and stop until we hit the Play button again.
  • BtnPrevious, BtnNext, BtnPlay, BtnPause - get or set the image for the Previous, Next, Play, and Pause buttons, respectively. These properties accept relative URLs or absolute URL paths to the button images. Make sure to place the images folder at the root directory of the application if you are using relative URLs.

The YsaSSModel class also contains a constructor with default value specified as part of the declaration. This will allow us to use optional and named arguments to instantiate the object. Please refer to listing 2.

Listing 2
 

public YsaSSModel(string xpath = "site", string xmlSource = "/YSASS/sites.xml",
     int width = 728, int height = 95,
     bool autoPlay = true, bool showNavigation = true,
     int delay_btw_slide = 10000, int fadeDuration = 2000,
     int cycles_before_stopping = 99,
     string btnPreviousImagePath = "/Content/ysaSS-images/previous.gif",
     string btnNextImagePath = "/Content/ysaSS-images/next.gif",
     string btnPlayImagePath = "/Content/ysaSS-images/play.gif",
     string btnPauseImagePath = "/Content/ysaSS-images/pause.gif")
 {
     XPath = xpath;
     XMLSource = xmlSource;
     Width = width;
     Height = height;
     AutoPlay = autoPlay;
     ShowNavigation = showNavigation;
     Delay_btw_slide = delay_btw_slide;
     FadeDuration = fadeDuration;
     Cycles_before_stopping = cycles_before_stopping;
     BtnPreviousImagePath = btnPreviousImagePath;
     BtnNextImagePath = btnNextImagePath;
     BtnPlayImagePath = btnPlayImagePath;
     BtnPauseImagePath = btnPauseImagePath;
     SSContainer = YsaSSHelper.CreateDiv(WrapperID);
     SSScript = YsaSSHelper.CreateScript(WrapperID, xmlSource, xpath, width, height, btnPreviousImagePath,
         btnPlayImagePath, btnNextImagePath, btnPauseImagePath, showNavigation, autoPlay,
         delay_btw_slide, cycles_before_stopping, fadeDuration);
}

Partial View/User Control

There are three lines in the user control page. The first line is the @model directive to reference YsaSSModel. The purpose of the second line is to render the Slideshow container and the last line is to render the JavaScript.

Listing 3
 

@model MvcSlideShow.Models.YsaSSModel
@Html.Raw(@Model.SSContainer)
@Html.Raw(@Model.SSScript) 

Controller

The controllers are very straight forward. Please refer to listing 3 for an example.

Listing 4
 

public ActionResult Example1() { return View(); }
public ActionResult Example2() { return View(); }
public ActionResult Example3() { return View(); }

Views

First thing we have to do before using the user control is to import the MvcSlideShow.Models namespace with the @using keyword. Then use the Html.Partial helper to render the partial view named "YsaUserControls/_YsaSS" inline. We don't have to specify the full path because the helper method will automatically assume that the partial view resides in the \Views\Shared\ folder. Example 1 demonstrates how to call the user control by passing the xmlSource, width, height and showNavigation named arguments to the model. Remember that the parameter's default value was specified in the constructor. So, the parameters are optional; if none are specified then the default value will be used instead. Last but not least, include the simplegallery.js JavaScript at the end of the view. Also ensure you have the jQuery library on the page/master page.

Example 1
 

 @using MvcSlideShow.Models
@Html.Partial("YsaUserControls/_YsaSS", new YsaSSModel(xmlSource: "/xml/sites.xml", width: 728,
height:90, showNavigation: false))
<script src="@Url.Content("~/Scripts/simplegallery.js")" type="text/javascript"></script> 

More Example
 

 @Html.Partial("YsaUserControls/_YsaSS", new YsaSSModel(xpath: "cat",xmlSource: "/xml/Cats.xml", width: 448,height:600))
@Html.Partial("YsaUserControls/_YsaSS", new YsaSSModel(xmlSource: "/xml/500x281.xml", width: 500, height:281, 
xpath: "site500x281", btnPauseImagePath:"/Content/YsaSS-images/pause2.png",
btnNextImagePath: "/Content/YsaSS-images/forward.png",btnPlayImagePath: "/Content/YsaSS-images/play2.png",
btnPreviousImagePath: "/Content/YsaSS-images/backward.png"))

Point of Interest

A couple of things worth mentioning here is how to route the request to the appropriate Areas/Structures based on the request URL and using the same controller name within the application. The attached example contains an area named "Photo" and a home controller. During runtime we will see the error "Multiple types were found that match the controller named 'Home. Well, that is reasonable because we have a controller with the name "Home" in both the Photo area and at the root level. To remedy this, include a constraint to the route with the namespace to the controllers in the Global.asax file. Refer to listing 5.

Listing 5
 

 routes.MapRoute("Default", // Route name"{controller}/{action}/{id}", 
// URL with parametersnew { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
new string[] { "MvcSlideShow.Controllers" }); 

Shown in listing 6 is how the route will look like if we include the constraint inside the PhotoAreaRegistration.

Listing 6
 

 context.MapRoute("myarea_default","Photo/{controller}/{action}/{id}",
new { action = "Index", controller = "Home", id = UrlParameter.Optional },new[] { "MvcSlideShow.Areas.Photo.Controllers" }); 

There is a controller called "Random" and a view named "Index" in the Photo area. We will get the error "The view 'Index' or its master was not found or no view engine supports the searched locations" if using the code in listing 7. This happens because the route is looking for the "Random" controller at the root level. The workaround for this error is to specify the area in the ActionLink method. Refer to listing 8.

Listing 7
 

 @Html.ActionLink("Example 4: Auto Play = false", "Index", "Random") 

Listing 8
 

 @Html.ActionLink("Example 4: Auto Play = false", 
"Index", "Random", new { area = "Photo" }, null) 

Conclusion

I would recommend downloading the demo and exploring it in order to grasp the full concept of it because I might have missed some important information in this article. I hope someone will find this information useful and make your programming job easier. If you find any bugs or disagree with the contents or want to help improve this article, please drop me a line and I'll work with you to correct it. Please send me an email if you want to help improve this article.

History

09/04/2012- First Release (v01.00.00)

Resources

http://www.primaryobjects.com/CMS/Article129.aspx
http://msdn.microsoft.com/en-us/library/ee461420%28VS.100%29.aspx#registering_area_routes
http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx

Demo

http://mvc.ysatech.com/jQuery_XML_SlideShow

Download

http://download.ysatech.com/jQueryXMLMvcSlideShow.zip


Similar Articles