你可以寫一個主題感知圖像幫手:
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中,或者甚至更好地使它成爲你的路線的一部分,在這種情況下你的網站將更加友好。
很酷。感謝SEO技巧。然而,我不明白這是如何更友好的搜索引擎優化 - 你能詳細說明這一點? – Unknown