Image button in ActionLink MVC
Asked Answered
D

3

9

How to put image instead text in ActionLink button:

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

So how to change text "Edit-link" to image?

Thanks for any idea.

Douche answered 8/5, 2014 at 7:44 Comment(0)
C
15

do like this:

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

or pass both action and controller name by using other 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 can reuse it in any View in 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 View:

@using MyApplication.Helpers;

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

Output HTML:

<a href="/ControllerName/ActionName">
  <img src="/images/untitled.png">
</a>
Creamery answered 8/5, 2014 at 9:10 Comment(1)
you have to pass your controllername hereCreamery
C
2

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

Compulsion answered 8/5, 2014 at 7:50 Comment(3)
so you put ...Replace("Edit-link", "img-source-here"?Douche
Parser Error Message: "<" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid.Douche
I fix Parser Error Message, but then appears this error: A route named 'Edit' could not be found in the route collection.Douche
F
0
 <a href="@Url.Action("Edit Link","Edit",new {id = item.EId })">
    <img src="@Url.Content("~/img/iconfinder_new-24_103173.png")" style="height:20px;width:20px;color:blue" title="Edit" />
 </a>

Try this code. It will add an image linked to the Edit() action with the id set.

Fife answered 6/5, 2020 at 5:36 Comment(1)
That should probably be new {id = user.userID } for consistency with the OP’s sample code.Umbilicus

© 2022 - 2024 — McMap. All rights reserved.