This tutorial will teach you how to display a random image on page load, and then keep that image until the sessions expires. Upon expiration a new random image will be chosen on a new session.

We will be using ASP.NET and C#; this will be done programmatically, thru the Code behind Page.

This tutorial will show how we can choose a random image to display on page load, and this same image will remain for the duration of the session. This means that no matter how many times the visitor refreshes the page; the image will remain the same. However, if the browser is closed and the session ends, a new image will be chosen at random upon a new session start, and remain until the session ends, again.

First we need to reference the System.IO Class in our code behind.

Go to your Default.aspx.cs and in the using statements add the line below.

Code Block
Default.aspx

It is extremely easy to use Visual Studio to build a new page.

using System.IO;

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect’s help, we were able to avoid any headaches!

In this example we will only be using a simple image tag to display the image on the webpage. Very little ASP.Net being used since everything is being done programmatically thru our code behind.

Code Block
Default.aspx.cs

<form id="form1" runat="server">
        <% Response.Write("<img src='" + chooseImage() + "' />");%>
</form>

We used over 10 web hosting companies before we found Server Intellect. They offer dedicated servers, and they now offer cloud hosting!

On page load, we will call the method to choose the background image at random, but only if an image has not yet been selected this session.

Code Block
Default.aspx

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        chooseImage();
    }
 

Let’s add an Images Folder to store the images

In your solution explorer right click on your website and select Add new folder.

Let’s name that new folder Media

Then right click on the Media folder and let’s add another folder and we can name that
folder img to store our random images.

Now let’s add the images to that folder. Right click on the img folder, and select add existing items, where you will find your images and at that point you may select your images.

Pro tip, it is suggested you name your images properly for whatever it is your trying to do, also it helps when trying find or call the images at a later time.

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

Now we will write the code to call on the images.

Now the next event, we will select the image from the img folder and here in this line of code you will specify the actual path.
Specify as a string, since you will be displaying an image.

The code-behind will look something like this:

Code Block
Function to retrieve the image from the images folder. 

    public string chooseImage()
    {
        if (Session["img"] == null)
        {
            string imgPath;
            int fileCount = Directory.GetFiles(Server.MapPath("/media/img/"), "*.*"SearchOption.TopDirectoryOnly).Length;
            fileCount = fileCount + 1;
            imgPath = "media/img/" + RandomNumber(1, fileCount) + ".jpg";
            Session["img"] = imgPath;
            return imgPath;
        }

Next we will want it to check if it’s the same images in a new sessions so let’s call an Else Statement and have it return a new image if the selected image has already been used in a previous session.

Code Block
Method to return the images randomly.

    else
            return Session["img"].ToString();
    }
 
    private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }
}

Completion

And It’s really that simple, we have successfully displayed a random image on page load, while also detecting if the image was used previously in another session by using the If and Else Statements. 

Please download our full source code to reference along with this tutorial.

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

randomimagesession-csharp (2).zip