Image button in ActionLink MVC

How to put an image instead of text in an ActionLink button:

@Html.ActionLink("Edit-link", "Edit", new { id=use.userID })

So, how to change the text "Change Link" to the image?

Thanks for any idea.

+4
source share
2 answers

follow these steps:

<a href="@Url.Action("Edit")" id="@use.userID">
<img src="@Url.Content("~/images/someimage.png")" />
</a>

or pass the name of the action and controller using another override:

<a href="@Url.Action("Edit","Controller")" id="@use.userID">
    <img src="@Url.Content("~/images/someimage.png")" />
    </a>

UPDATE:

You can also create a custom Html Helper and you can reuse it in any view in the application:

namespace MyApplication.Helpers
{
  public static class CustomHtmlHelepers
  {
    public static IHtmlString ImageActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes,string imageSrc)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var img = new TagBuilder("img");
        img.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc));
        var anchor = new TagBuilder("a") { InnerHtml = img.ToString(TagRenderMode.SelfClosing) };
        anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
        anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        return MvcHtmlString.Create(anchor.ToString());

    }
  }
}

and use it in the view:

@using MyApplication.Helpers;

@Html.ImageActionLink("LinkText","ActionName","ControllerName",null,null,"~/images/untitled.png")

HTML output:

<a href="/ControllerName/ActionName">
  <img src="/images/untitled.png">
</a>
+10
source

Try this code:

@Html.Raw(@Html.ActionLink("Edit-link","Edit", new { id=use.userID }).ToHtmlString().Replace("Edit-link", "<img src=\"/Contents/img/logo.png\" ... />"))

or

enter image description here

+2

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


All Articles