这可能是一个非常简单的问题。如何将图像添加到Html.ActionLink
链接?在常规的 HTML 中,我只想写下这样的内容:
<a href="url"><img src="whatever.jpg" />Words and Stuff too </a>
如何在生成的链接标记中嵌入图像?
@Html.ActionLink("Change Database Connection","Index","Home",null,null)
我试过这个
@Html.ActionLink("<img src=\"../../Content/themes/base/images/web_database.png\" />Change Database Connection","Index","Home",null,null)
显然这不起作用。它只是以纯文本显示我的img
标签。实现这一目标的正确方法是什么?我是否需要一个帮助类来做这么简单的事情?
答案 0 :(得分:4)
以下是我采用和更新的两个扩展程序。
public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string imageUrl, string altText, string actionName, string controller, object routeValues, string _imageClass = "", object htmlAttributes = null)
{
var image = new TagBuilder("img");
image.MergeAttribute("src", imageUrl);
image.MergeAttribute("alt", altText);
if (string.IsNullOrEmpty(_imageClass) == false) image.MergeAttribute("class", _imageClass);
var link = helper.ActionLink("[replaceme]", actionName, controller, routeValues, htmlAttributes);
return new MvcHtmlString(link.ToHtmlString().Replace("[replaceme]", image.ToString(TagRenderMode.SelfClosing)));
}
public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string imageUrl, string altText, RouteValueDictionary routeValues, string _imageClass = "", object htmlAttributes = null)
{
var image = new TagBuilder("img");
image.MergeAttribute("src", imageUrl);
image.MergeAttribute("alt", altText);
if (string.IsNullOrEmpty(_imageClass) == false) image.MergeAttribute("class", _imageClass);
var link = helper.ActionLink("[replaceme]", routeValues, htmlAttributes);
return new MvcHtmlString(link.ToHtmlString().Replace("[replaceme]", image.ToString(TagRenderMode.SelfClosing)));
}