This tutorial shows how to display a random image
upon page load, and then keep that image until the session expires. A
new random image will be chosen on new sessions, and remain. C# version.
Displaying a Random Image Each New Session ASP.NET & C#
This tutorial shows how to display a random image upon page load, and
then keep that image until the session expires. A new random image will
be chosen on new sessions, and remain. C# version.
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 use System.IO:
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.
For this example, we will simply use an IMG tag:
| <form id="form1" runat="server">
<% Response.Write("<img src='" + chooseImage() + "' />");%>
</form> |
We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.
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.
The code-behind will look something like this:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
chooseImage();
}
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;
}
else
return Session["img"].ToString();
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
} |
|