2010-07-17 34 views
0

我想弄清楚如何做一個服務器ASP.NET MVC圖像加載刷新。基本上,我有一個圖像陣列,我想旋轉頁面上的刷新。我知道如何在jQuery中做到這一點,但問題是,所有圖像同時加載[這在性能方面很糟糕]刷新ASP.NET MVC圖像加載

有誰知道我該怎麼做?

目前JS看起來像下面,但我真的希望它的服務器端:

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

+0

什麼*刷新*?你有哪些圖像陣列?你的代碼是怎樣的? – 2010-07-17 07:39:18

+0

嗨 - 我添加了JS我有。但它不是服務器端,所以三個圖像加載? – Tom 2010-07-17 07:49:45

回答

2

如何寫一個幫手:

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

,你可以在頁面中使用:

<%= Html.RandomImage() %> 

如果你也想產生一個錨:

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()); 
    } 
} 
+0

哦傳說!非常感謝 :))))) – Tom 2010-07-17 08:34:59