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. VB 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:
| Imports System.IO |
We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with!
For this example, we will simply use an IMG tag:| <form id="form1" runat="server"> <% Response.Write("<img src='" + chooseImage() + "' />")%> </form> |
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.
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:
| Imports System.IO Partial Class _Default Inherits System.Web.UI.Page End Class Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load chooseImage() End SubPublic Function chooseImage() As String If Session("img") Is Nothing Then End FunctionDim imgPath As String Else Dim fileCount As Integer = Directory.GetFiles(Server.MapPath("/media/img/"), "*.*", SearchOption.TopDirectoryOnly).Length fileCount = fileCount + 1 imgPath = "media/img/" & RandomNumber(1, fileCount) & ".jpg" Session("img") = imgPath Return imgPath Return Session("img").ToString() End IfPrivate Function RandomNumber(ByVal min As Integer, ByVal max As Integer) As Integer Dim random As New Random() End FunctionReturn random.Next(min, max) |
No comments:
Post a Comment