views:

40

answers:

1

Hi Guys,

I am trying to figure out how to do a server ASP.NET MVC Image Load on Refresh. Basically, I have an array of image's I would like to rotate on refresh on the page. I know how to do this in jQuery but the problem is that all images load at the same time [which sucks in terms of performance]

Does anyone know how I could do this ?

Currently JS looks like below but I really want it server-side:

function random_imglink(){
  var myimages=new Array()
  //specify random images below. You can have as many as you wish
  myimages[1]="img1.gif"
  myimages[2]="img2.gif"
  myimages[3]="img3.gif"

  //specify corresponding links below
  var imagelinks=new Array()
  imagelinks[1]="http://www.example1.com/"
  imagelinks[2]="http://www.example2.com"
  imagelinks[3]="http://www.example3.com"

  var ry=Math.floor(Math.random()*myimages.length)

  if (ry==0)
     ry=1
     document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}

  random_imglink()

Thx

+1  A: 

How about writing a helper:

private static Random _random = new Random();
public static MvcHtmlString RandomImage(this HtmlHelper htmlHelper)
{
    var img = new TagBuilder("img");
    var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
    var number = _random.Next(1, 4);
    var src = urlHelper.Content(string.Format("~/img{0}.gif", number));
    img.Attributes["src"] = src;
    img.Attributes["border"] = "0";
    return MvcHtmlString.Create(img.ToString());
}

Which you could use in your page:

<%= Html.RandomImage() %>

And if you want to also generate an anchor:

public static class HtmlExtensions
{
    private class Image
    {
        public string Src { get; set; }
        public string Href { get; set; }
    }

    private static Random _random = new Random();
    private static Image[] _images = new[]
    {
        new Image { Src = "img1.gif", Href = "http://www.example1.com" },
        new Image { Src = "img2.gif", Href = "http://www.example2.com" },
        new Image { Src = "img3.gif", Href = "http://www.example3.com" }
    };

    public static MvcHtmlString RandomImage(this HtmlHelper htmlHelper)
    {
        var anchorTag = new TagBuilder("a");
        var randomImage = _images[_random.Next(0, _images.Length)];
        anchorTag.Attributes["href"] = randomImage.Href;

        var imageTag = new TagBuilder("img");
        imageTag.Attributes["src"] = randomImage.Src;
        imageTag.Attributes["border"] = "0";
        anchorTag.InnerHtml = imageTag.ToString();
        return MvcHtmlString.Create(anchorTag.ToString());
    }
}
Darin Dimitrov
oh legend! thanks so much :)))))
Tom