Joe Healy (http://www.devfish.net) came to Orlando today to talk about ASP.NET AJAX (http://ajax.asp.net). After seeing his presentation I was inspired to play with the tools. Additionally I got an email asking that I build an image rotator that changed the images on a webpage every 5 seconds. I thought to myself, self I can do that with AJAX, so I did, and I thought I would share it with you.
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.
Thanks Joe for coming out to speak to ONETUG!
1 2 3 4 5 6 7 8 9 10 11 12 |
<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> |
1 2 3 4 5 6 7 8 9 10 11 12 |
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; } |