Home > AJAX, ASP.Net > Display Random Image with AJAX

Display Random Image with AJAX


Hi

try this example:

First I added a ScriptManager and UpdatePanel to the page, inside the ContentTemplate area of the UpdatePanel I added an AJAX Timer and an ASP image. Next I set the interval property to the number of milliseconds I wanted each picture to be visible. Now in the code behind I created a method that set the url property of the image to a random image from my images folder. I now call that method from the page load event and like magic you have a simple random image rotator in ASP.NET AJAX.

<form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server"
                     Interval="5000">
                </asp:Timer>
                <asp:Image runat="server" ID="img" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>

and in code behind:-

protected void Page_Load(object sender, EventArgs e)
    {
        SetNextImage();
    }
    private void SetNextImage()
    {
        string path = Server.MapPath("~/Image/");
        string[] files = Directory.GetFiles(path);
        Random r = new Random();
        FileInfo fi = new FileInfo(files[r.Next(0, files.Length)]);
        img.ImageUrl = "~/Image/" + fi.Name;
    }

Don’t forget to add using System.IO;
Hope this helps
Good Luck

Advertisements
Categories: AJAX, ASP.Net
  1. sergeos
    February 7, 2009 at 11:01 am
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            SetNextImage()
        End Sub
    
        Private Sub SetNextImage()
    
            Dim path As String = Server.MapPath("~/Images/")
            Dim files As String() = Directory.GetFiles(path)
            Dim r As Random = New Random()
            Dim fi As FileInfo = New FileInfo(files(r.Next(0, files.Length)))
            img.ImageUrl = "~/Images/" + fi.Name
        End Sub
  2. yasserzaid
    December 7, 2009 at 8:20 am

    Thanks sergeos

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: