How to make an image part of my html.ActionLink?

This is probably a very simple question. How to add an image to the Html.ActionLink link? In regular HTML, I would just add something like this:

  <a href="url"><img src="whatever.jpg" />Words and Stuff too </a> 

How can I embed an image in a generated link tag?

  @Html.ActionLink("Change Database Connection","Index","Home",null,null) 

I tried to do it

  @Html.ActionLink("<img src=\"../../Content/themes/base/images/web_database.png\" />Change Database Connection","Index","Home",null,null) 

Obviously, this did not work. It just displayed the img tag as plain text. What is the right way to achieve this? Will I need a helper class for something so simple?

+4
source share
1 answer

Here are two extensions that I have accepted and updated.

 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))); } 
+4
source

Source: https://habr.com/ru/post/1381790/


All Articles