Click here to Skip to main content
Licence BSD
First Posted 2 Oct 2008
Views 21,013
Downloads 535
Bookmarked 22 times

A simple ASP.NET AJAX image browser

By Ole L. Sørensen | 2 Oct 2008
An article on showing an image browser in a web page using ASP.NET and AJAX.
1 vote, 10.0%
1

2
1 vote, 10.0%
3
6 votes, 60.0%
4
2 votes, 20.0%
5
3.35/5 - 10 votes
μ 3.35, σa 1.99 [?]

Introduction

I have written an image browser page with ASP.NET, using ASP.NET AJAX to retrieve information about the images on the server. Images are displayed using a single ASPX page and a folder with JPG files. The code-behind is written in C#. No database is involved.

Background

My goal was to show my family some photos on a web page, and hopefully spending less than a few hours accomplishing that. I wanted to do so without using a database, without titles, without descriptions, without tags, etc. However, I included the shooting date of the photo as part of the file name, since it provided a way to retain some information without using a database.

Using the code

Code-behind (C#)

I first created an ASPX web form, and in the code-behind, wrote a static web method to return information about the images on the server:

[WebMethod]
public static Image[] GetImages()
{
    // The virtual path to the image folder:
    // (in this case a folder that contains some photos)
    string imageFolderVirtualPath = "~/Photos/";
    string imageFolderPath = HttpContext.Current.Server.MapPath(imageFolderVirtualPath);
    List<image> images = new List<image>();
    DirectoryInfo diImages = new DirectoryInfo(imageFolderPath);
    // Only *.jpg files are included in this case:
    foreach (FileInfo fiImage in diImages.GetFiles("*.jpg"))
    {
        string fileName = fiImage.Name;
        // If the file name starts with the DateTime pattern yyyy-MM-dd,
        // the date is parsed from that:
        string date = string.Empty;
        int year = 0;
        int month = 0;
        int day = 0;
        if (fileName.Length > 9 && Int32.TryParse(fileName.Substring(0, 4), out year)
            && Int32.TryParse(fileName.Substring(5, 2), out month)
            && Int32.TryParse(fileName.Substring(8, 2), out day))
        {
            date = new DateTime(year, month, day).ToLongDateString();
        }
        images.Add(new Image
        {
            Date = date,
            VirtualPath = CombineVirtualPaths(imageFolderVirtualPath, fileName)
        });
    }
    return images.ToArray();
}

A helper method combines the virtual paths:

private static string CombineVirtualPaths(string virtualPath1, string virtualPath2)
{
    return string.Format("{0}/{1}", virtualPath1.Trim('~', '/'), virtualPath2.Trim('/'));
}

A helper class provides information about an image:

public class Image
{
    /// <summary>
    /// The virtual path to the image file
    /// </summary>
    public string VirtualPath { get; set; }

    /// <summary>
    /// The date as a string
    /// </summary>
    public string Date { get; set; }
}

HTML/ASPX markup

In the *.aspx file, I have the following markup:

<body onload="GetImages();">
<form id="form1" runat="server">
<asp:ScriptManager id="sm1" runat="server" 
   EnablePageMethods="true" EnableScriptGlobalization="true">
</asp:ScriptManager>
<div>
 <div id="divButtons" style="float: left;">
 </div>
 <div id="divImage" style="float: left;">
 </div>
</div>
</form>
</body>

JavaScript

On page load, a JavaScript method is fired that retrieves info from the page method:

 // Information about the Images:
 var images;

 // The index of the currently shown Image:
 var currentImageIndex = 0;

 // Calls the page method to obtain information about the Images:
 function GetImages() {
     PageMethods.GetImages(GetImagesCompleted);
 }

 // The call-back where information about the images is returned:
 function GetImagesCompleted(result) {
     images = result;
     ShowImage();
 }

 // Shows the Image:
 function ShowImage() {
     var currentImage = images[currentImageIndex];
     var date = currentImage.Date;
     var imgImage = "<img id='imgImage' alt='" + date +
         "' title='" + date + "' src='" + 
         currentImage.VirtualPath "' />";
     var dp = document.getElementById("divImage");
     dp.innerHTML = imgImage;
     document.title = date;
     ShowButtons();
 }

A separate JavaScript method displays the appropriate navigation buttons:

  // Shows the buttons:
 function ShowButtons() {
     // Gets localized texts (English or Danish) for the buttons.
     // This only works with the following two settings:
     //    - The ScriptManager on this page must have:
     ///     EnableScriptGlobalization="true"
     //    - web.config must have:
     //      <globalization culture="auto"> (in <system.web> section)
     // The default English texts:
     var first = "First";
     var previous = "Previous";
     var next = "Next";
     var last = "Last";
     if (Sys.CultureInfo.CurrentCulture.name.toLowerCase().startsWith("da")) {
         // The Danish texts:
         first = "Første";
         previous = "Forrige";
         next = "Næste";
         last = "Sidste";
     }
     var button1 = "<div><input type='button' style='width: 75px;'";
     var btnFirst = button1 + " value='" + first + 
                    "' onclick='ShowFirstImage();'";
     var btnPrevious = button1 + " value='" + previous + 
                       "' onclick='ShowPreviousImage();'";
     var btnNext = button1 + " value='" + next + 
                   "' onclick='ShowNextImage();'";
     var btnLast = button1 + " value='" + last + 
                   "' onclick='ShowLastImage();'";
     if (currentImageIndex == 0) {
         btnFirst += " disabled='disabled'";
         btnPrevious += " disabled='disabled'";
     }
     if (currentImageIndex == images.length - 1) {
         btnNext += " disabled='disabled'";
         btnLast += " disabled='disabled'";
     }
     var button2 = " /></div>";
     btnFirst += button2;
     btnPrevious += button2;
     btnNext += button2;
     btnLast += button2;
     var db1 = document.getElementById("divButtons");
     db1.innerHTML = btnFirst + btnPrevious + btnNext + btnLast;
 }

 // Shows the first Image:
 function ShowFirstImage() {
     currentImageIndex = 0;
     ShowImage();
 }

 // Shows the previous Image:
 function ShowPreviousImage() {
     if (currentImageIndex > 0) {
         currentImageIndex -= 1;
         ShowImage();
     }
 }

 // Shows the next Image:
 function ShowNextImage() {
     if (currentImageIndex < images.length - 1) {
         currentImageIndex += 1;
         ShowImage();
     }
 }

 // Shows the last image:
 function ShowLastImage() {
     currentImageIndex = images.length - 1;
     ShowImage();
 }

Points of interest

  • A useful application built in a single web form and a folder with images.
  • The EnableScriptGlobalization feature on the ScriptManager and the ability to extract language information in JavaScript using Sys.CultureInfo.CurrentCulture.name.

License

This article, along with any associated source code and files, is licensed under The BSD License

About the Author

Ole L. Sørensen

Software Developer

Denmark Denmark

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionIs this .NET 3.5? Pinmemberremarkpk119:09 5 Mar '09  
GeneralAlternative to parse the filename for a date pattern PinmemberNorbert Bietsch10:15 2 Oct '08  
Hi, thanks for sharing your code, I'll have a closer look Wink | ;)
With the way you parse for a date pattern in the filename you are at risk for an exception in case the integers don't combine to a valid date. Lately I did something similar and I chose DateTime.TryParseExact for it:
string fileName = "2008-01-30_bananaglasses.jpg";
DateTime outDate;
if (fileName.Length > 9 && DateTime.TryParseExact(fileName.Substring(0, "yyyy-MM-dd".Length), new[] { "yyyy-MM-dd" }, System.Threading.Thread.CurrentThread.CurrentCulture,
System.Globalization.DateTimeStyles.None, out outDate))
     {
          date = outDate.ToLongDateString();
     }
Nothing spectacular, but maybe more safe.
Thanks again,
Norbert
AnswerRe: Alternative to parse the filename for a date pattern PinmemberOle L. Sørensen19:53 2 Oct '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 2 Oct 2008
Article Copyright 2008 by Ole L. Sørensen
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid