Display a dynamic selection of images from a folder in ASP.NET based on the option chosen in a dropdown list

Is there a way to dynamically load multiple images from a folder in ASP.Net based on the selected option in a dropdown list? I'm trying to implement this in Visual Studio and need some help. Below is the code I've been working with, but I'm open to suggestions for improvement or modifications. Additionally, I want to bind the image output to an image button control as a slideshow.

 <script type="text/javascript">
   function new1(city) {
      switch (city) {
           case "Patna":
               var imlocation = "Patna/";
               var currentdate = 0;
               var image_number = 0;
               function ImageArray(n) {
                   this.length = n;
                   for (var i = 1; i <= n; i++) {
                       this[i] = ' '
                   }
               }
               image = new ImageArray(2)
               image[0] = '2.jpg'
               image[1] = '3.jpg'
               var rand = 60 / image.length
               function randomimage() {
                   currentdate = new Date()
                   image_number = currentdate.getSeconds()
                   image_number = Math.floor(image_number / rand)
                   return (image[image_number])
               }
                                  document.write("<img src='" + imlocation + randomimage() + "'>");

           case "Bhopal":
               var imlocation1 = "Bhopal/";
               var currentdate1 = 0;
               var image_number1 = 0;
               function ImageArray1(n) {
                   this.length = n;
                   for (var i = 1; i <= n; i++) {
                       this[i] = ' '
                   }
               }
               image1 = new ImageArray1(3)
               image1[0] = '2.jpg'
               image1[1] = '4.jpg'
               image1[2] = '1.jpg'
               var rand1 = 100/ image1.length
               function randomimage1() {
                   currentdate1 = new Date()
                   image_number1 = currentdate1.getSeconds()
                   image_number1 = Math.floor(image_number1 / rand1)
                   return (image1[image_number1])
               }
               document.write("<img src='" + imlocation1 + randomimage1() + "'>");

       }
   }

<asp:DropDownList ID="DropDownList1" runat="server" onchange="new1(this.value)"
                DataSourceID="SqlDataSource1" DataTextField="City" DataValueField="City" 
                onselectedindexchanged="DropDownList1_SelectedIndexChanged" 
                AutoPostBack="True" >
            </asp:DropDownList>

Answer №1

After a long search, I have finally found a solution for this problem by using the ajax slideshow extender. Below is the code that needs to be implemented in the webservice.

[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [System.Web.Services.WebMethod()]
    [System.Web.Script.Services.ScriptMethod]
    public AjaxControlToolkit.Slide[] GetSlides(string contextKey)
    {

        string[] imagenames = System.IO.Directory.GetFiles(HttpContext.Current.Server.MapPath("~/" + contextKey ));
        AjaxControlToolkit.Slide[] photos = new AjaxControlToolkit.Slide[imagenames.Length];
        for (int i = 0; i < imagenames.Length; i++)
        {
            string[] file = imagenames[i].Split('\\');
            photos[i] = new AjaxControlToolkit.Slide(contextKey + "/" + file[file.Length - 1], file[file.Length - 1], "");
        }
        return photos;

    }

}

To implement the slideshow extender, use the following code:

<asp:SlideShowExtender ID="SlideShowExtender1" TargetControlID="Image1" SlideShowServiceMethod="GetSlides" SlideShowServicePath="~/WebService1.asmx" Loop="true" runat="server" UseContextKey="true" 
AutoPlay="True" BehaviorID="b1">        
</asp:SlideShowExtender>

Finally, in the page_load event:

 if (Page.IsPostBack)
{
    SlideShowExtender1.ContextKey = DropDownList1.SelectedValue;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing automatic line breaks in Bootstrap

When setting the "overflow scroll able" option, I want it to only allow scrolling in the y direction and if x content overflows, a line break should occur. I tried applying 'white-space', but it didn't work as expected. <ul class="s ...

"An intermittent error is occurring with the jQuery webcam plugin, where a TypeError is being thrown stating that

Many times, I encounter the error stated in the subject line. The code snippet where this error occurs is within the else section of the function below: if ($('#clicktosnap').is('.disabled')) { alert ("Please enable the camera first, ...

JWT refresh and access tokens: A dynamic duo for secure authentication

In my project, I utilize jwt tokens with a strategic approach. Long-lived refresh tokens are employed for authentication purposes, while short-lived access tokens are used to safeguard protected resources. To enhance security against xss attacks, the refre ...

Executing Oracle Package: ORA-06550 or ORA-06502

Whenever I attempt to execute a package on our Oracle database using either Oracle's .NET provider or Microsoft's Oracle provider, I encounter the following error message: {"ORA-06550: line 1, column 7:\nPLS-00221: 'BEGIN_TRANSACTION& ...

Utilizing the DISTINCT keyword in T-SQL to retrieve unique data

I'm dealing with a table containing date time and string columns. Multiple entries can share the same string (file path). My goal is to retrieve unique entries with the latest date time stamp. Can anyone offer assistance? Cheers. EDIT: Here's ...

jQuery code unable to alter the class of a div

Need help with a script on my single page site that adds a "read more" style link to a content area's div. The goal is for the button to change the class of the content area when clicked, showing all of the content. Clicking again should hide the cont ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

Unusual behavior in sorting values with JavaScript

I have spent hours trying to figure this out, and the only conclusion I can come to is that when there are 14 elements to sort, it doesn't function properly, but with thirteen elements, it works perfectly. My goal is to sort DIV elements based on the ...

Leveraging User Location in Angular 6 using API with OpenLayers

I am currently developing a mapping application using Angular (6) and OpenLayers (4.6.5) with the initial aim of retrieving user geolocation. To achieve this, I am utilizing a French API provided by the French Government for querying and obtaining GeoJSON ...

Having issues with WP7 and MethodAccessException when using Type.GetMethods? Wondering if there's a solution to this bug?

Trying to generate a list of all methods of a type using the GetMethods method, it appears to be incorrectly implemented. The issue arises when there is an overridden generic method on the reflected type, causing a MethodAccessException to be thrown. Is t ...

The JQuery button fails to activate the service call through Ajax

I'm facing an issue with my JSON service while trying to make an AJAX call using jQuery on a webpage. Even though I have created a button and attempted to trigger the click event, I am not receiving any alert message and the service call itself is not ...

Retrieving the class ID when clicked

In my PHP while loop, I am generating multiple classes to display information (such as user posts) along with two buttons at the bottom of each post. One button increments and the other decrements a numerical value. I am trying to figure out how to retri ...

Parsing PHP array using JavaScript

$namesSelect = "SELECT username FROM users"; $names = mysql_query($namesSelect); $nameCheck = mysql_fetch_array($names) This code snippet retrieves all usernames from the users table and stores them in the $names array. I am now faced with the task of ...

Extracting text from an array within Meteor

I am currently utilizing Meteor along with the ajduke:bootstrap-tagsinput plugin for managing tags on my platform. Check out the ajduke:bootstrap-tagsinput example page here For inserting tags as arrays, I am using the True Multiple Value feature mention ...

Unable to execute and map the array promise of a POST request

I am facing an issue with my API called getQuote and a component named QuoteCard. Within the QuoteCard, I am attempting to display an array of users who liked a specific quote. The API is functioning properly, as verified through testing, and the code snip ...

Is it advisable to utilize a derived table in this specific scenario?

Currently, I'm facing a challenge where I need to retrieve 10 random rows from a table. The query I have been using seems inefficient and slow especially when dealing with larger datasets: SELECT `title` FROM table1 WHERE id1 = 10527 and id2 = 37821 ...

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

Applying a loop to fill a table in PL/SQL

I have a single-column table named x with number data type. I am trying to figure out how to populate this table with values in consecutive rows using a code similar to the one below. create table sometable (x number); begin for i .. X loop EXECUTE IMM ...

Issues arise when attempting to run JQuery functions with the $ symbol in the head tag of HTML

Because of the limitations imposed by Squarespace, I am only able to include code via the Head tag. When the script reaches the $ part of JQuery, it seems to not execute at all. After testing with numerous console.log() statements, I observed that the webp ...

What is the best way to incorporate one ObservableCollection into another ObservableCollection?

Currently, I am developing an app called Unsplash for UWP Windows 10. However, I am facing an issue where the response is limited to only 30, and I am unable to retrieve all the information. Thank you in advance for your assistance. public static Observ ...