Server Intellect
 
Home   Asp.Net Tutorials   What's New   Newsletter   More Resources
 
 
  Categories
Advanced Technologies
AJAX
Internet Browsers
Controls
Database
Email
Error Handling
File
Graphics
Website Navigation
Network
Performance
User Interface and Themes
Validation
Visual Web Developer
Web Services
XML
Suggest Tutorial


Navigator: Home - Tutorials - Graphics - Displaying a Random Image Each New Session ASP.NET & C#
Displaying a Random Image Each New Session ASP.NET & C#


ASP.NET Graphics Tutorial

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.

Download the Full Working Version of this Project written with Visual Studio.NET C# 2005 Here!

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

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:

using System.IO;

For this example, we will simply use an IMG tag:

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

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);
}
}

Download the Full Working Version of this Project written with Visual Studio.NET C# 2005 Here!

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!





 
  Developer Resources







Server Intellect Rocks