如何从CSS精灵创建ActionImage

本文关键字:创建 ActionImage 精灵 CSS | 更新日期: 2023-09-27 18:21:33

这是我上一个问题的后续:如何将图标集上的区域映射到按钮?

为了创建一个ActionImage链接,我决定制作自己的HtmlHelper扩展,所以我删除了so上发布的一些流行扩展,得到了这个:

// Controller/Action Image Link
public static MvcHtmlString ActionImage(this HtmlHelper html, 
    string controller, string action, object routeValues, 
    string imageSrc, string alternateText, object imageAttributes)
{
    UrlHelper url = new UrlHelper(html.ViewContext.RequestContext);
    // build the <img> tag
    TagBuilder imgBuilder = new TagBuilder("img");
    imgBuilder.MergeAttribute("src", url.Content(imageSrc));
    imgBuilder.MergeAttribute("alternateText", alternateText);
    string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
    // build the <a> tag
    TagBuilder anchorBuilder = new TagBuilder("a");
    anchorBuilder.MergeAttribute("href", url.Action(action, controller, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
    return MvcHtmlString.Create(anchorHtml);
}

现在,问题是我有一个CSS Sprite,我不知道如何使用ActionImage扩展方法:

@Html.ActionImage("Account", "LogOn", null, Sprite.Image("~/App_Sprites/twitterlogin.png"), "", null)

我尝试调用sprite的ToString()方法,但它没有返回URL。有其他方法可以做到这一点吗?

如何从CSS精灵创建ActionImage

您可以只传递到sprite的路径:

@Html.ActionImage(
    "Account", 
    "LogOn", 
    null, 
    "~/App_Sprites/twitterlogin.png", 
    "", 
    null
)

然后让助手负责使用Sprite.Image助手:生成图像

public static MvcHtmlString ActionImage(this HtmlHelper html, 
    string controller, string action, object routeValues, 
    string imageSrc, string alternateText, object imageAttributes)
{
    UrlHelper url = new UrlHelper(html.ViewContext.RequestContext);
    // build the <img> tag
    string img = Sprite.Image(imageSrc).ToHtmlString();
    // build the <a> tag
    TagBuilder anchorBuilder = new TagBuilder("a");
    anchorBuilder.MergeAttribute("href", url.Action(action, controller, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
    return MvcHtmlString.Create(anchorHtml);
}