Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image button in ActionLink MVC

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.

like image 434
Daniel K Rudolf_mag Avatar asked May 08 '14 07:05

Daniel K Rudolf_mag


People also ask

What is the use of ActionLink in MVC?

ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

How do you link a button in HTML?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.


2 Answers

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

like image 40
Kumar Manish Avatar answered Sep 28 '22 07:09

Kumar Manish


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>
like image 68
Ehsan Sajjad Avatar answered Sep 28 '22 07:09

Ehsan Sajjad