2012-11-16 26 views
0

根據所選主題更改圖像來源的最佳方法是什麼?理想情況下,您只需爲每個主題設置一個CSS,然後將圖像設置爲背景(這是我目前所做的)。根據主題在ASP.NET MVC中更改圖像

但是我現在需要做的是使用實際的圖像,它是功能性的,並且是演示文稿的一部分,它不僅僅是作爲設計一部分的圖像。根據主題,該圖像看起來會略有不同。

我正在保存每個用戶在數據庫中選擇的主題。我希望能夠在用戶根據數據庫中的主題請求頁面時更改圖像的來源。我正在使用依賴注入(StructureMap),MVC 4和EF 5.我想以某種方式將值分配給ViewBag.MyImagePath在我的_Layout頁面,然後所有頁面只有src =「@ ViewBag.MyImagePath」。

回答

1

你可以寫一個主題感知圖像幫手:

public static class HtmlExtensions 
{ 
    public static IHtmlString ThemeAwareImage(
     this HtmlHelper htmlHelper, 
     string image, 
     string alt = "" 
    ) 
    { 
     var context = htmlHelper.ViewContext.HttpContext; 
     var theme = context.Session["theme"] as string; 
     if (string.IsNullOrEmpty(theme)) 
     { 
      // the theme was not found in the session 
      // => go and fetch it from your dabatase 
      string currentUser = context.User.Identity.Name; 
      theme = GetThemeFromSomeDataStore(currentUser); 

      // cache the theme in the session for subsequent calls 
      context.Session["theme"] = theme; 
     } 

     var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); 
     var img = new TagBuilder("img"); 
     img.Attributes["alt"] = alt; 
     img.Attributes["src"] = urlHelper.Content(
      string.Format("~/images/{0}/{1}", theme, image) 
     ); 
     return new HtmlString(img.ToString(TagRenderMode.SelfClosing)); 
    } 
} 

可能在您的視圖中使用這些圖像渲染:

@Html.ThemeAwareImage("foo.jpg", "This is the foo image") 

作爲一個更好的替代品使用Session存儲目前的用戶主題,你可以將它緩存在一個cookie中,或者甚至更好地使它成爲你的路線的一部分,在這種情況下你的網站將更加友好。

+0

很酷。感謝SEO技巧。然而,我不明白這是如何更友好的搜索引擎優化 - 你能詳細說明這一點? – Unknown