Html.ActionLink as a button or an image, not a link

asp.net MvcActionlink

asp.net Mvc Problem Overview


In the latest (RC1) release of ASP.NET MVC, how do I get Html.ActionLink to render as a button or an image instead of a link?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

I like to use Url.Action() and Url.Content() like this:

<a href='@Url.Action("MyAction", "MyController")'>
    <img src='@Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>

Strictly speaking, the Url.Content is only needed for pathing is not really part of the answer to your question.

Thanks to @BrianLegg for pointing out that this should use the new Razor view syntax. Example has been updated accordingly.

Solution 2 - asp.net Mvc

Late response but you could just keep it simple and apply a CSS class to the htmlAttributes object.

<%= Html.ActionLink("Button Name", "Index", null, new { @class="classname" }) %>

and then create a class in your stylesheet

a.classname
{
	background: url(../Images/image.gif) no-repeat top left;
     display: block;
     width: 150px;
     height: 150px;
     text-indent: -9999px; /* hides the link text */
}

Solution 3 - asp.net Mvc

Borrowing from Patrick's answer, I found that I had to do this:

<button onclick="location.href='@Url.Action("Index", "Users")';return false;">Cancel</button>

to avoid calling the form's post method.

Solution 4 - asp.net Mvc

Call me simplistic, but I just do:

<a href="<%: Url.Action("ActionName", "ControllerName") %>">
    <button>Button Text</button>
</a>

And you just take care of the hyperlink highlight. Our users love it :)

Solution 5 - asp.net Mvc

Using bootstrap this is the shortest and cleanest approach to create a link to a controller action that appears as a dynamic button:

<a href='@Url.Action("Action", "Controller")' class="btn btn-primary">Click Me</a>

Or to use Html helpers:

@Html.ActionLink("Click Me", "Action", "Controller", new { @class = "btn btn-primary" })

Solution 6 - asp.net Mvc

if you don't want to use a link, use button. you can add image to button as well:

<button type="button" onclick="location.href='@Url.Action("Create", "Company")'" >
   Create New
   <img alt="New" title="New" src="~/Images/Button/plus.png">
</button>

type="button" performs your action instead of submitting form.

Solution 7 - asp.net Mvc

Just simply :

<button onclick="@Url.Action("index", "Family", new {familyid = Model.FamilyID })">Cancel</button>

Solution 8 - asp.net Mvc

A late answer but this is how I make my ActionLink into a button. We're using Bootstrap in our project as it makes it convenient. Never mind the @T since its only an translator we're using.

@Html.Actionlink("Some_button_text", "ActionMethod", "Controller", "Optional parameter", "html_code_you_want_to_apply_to_the_actionlink");

The above gives a link like this and it looks as the picture below:

localhost:XXXXX/Firms/AddAffiliation/F0500

![picture demonstrating button with bootstrap][1]

In my view:

@using (Html.BeginForm())
{
<div class="section-header">
    <div class="title">
        @T("Admin.Users.Users")
    </div>
    <div class="addAffiliation">
        <p />
        @Html.ActionLink("" + @T("Admin.Users.AddAffiliation"), "AddAffiliation", "Firms", new { id = (string)@WorkContext.CurrentFirm.ExternalId }, new { @class="btn btn-primary" })
    </div>
</div>

}

Hope this helps somebody [1]: http://i.stack.imgur.com/su0dO.png

Solution 9 - asp.net Mvc

You can't do this with Html.ActionLink. You should use Url.RouteUrl and use the URL to construct the element you want.

Solution 10 - asp.net Mvc

A simple way to do make your Html.ActionLink into a button (as long as you have BootStrap plugged in - which you probably have) is like this:

@Html.ActionLink("Button text", "ActionName", "ControllerName", new { @class = "btn btn-primary" })

Solution 11 - asp.net Mvc

<button onclick="location.href='@Url.Action("NewCustomer", "Customers")'">Checkout >></button>

Solution 12 - asp.net Mvc

Even later response, but I just ran into a similar issue and ended up writing my own Image link HtmlHelper extension.

You can find an implementation of it on my blog in the link above.

Just added in case someone is hunting down an implementation.

Solution 13 - asp.net Mvc

<li><a href="@Url.Action(  "View", "Controller" )"><i class='fa fa-user'></i><span>Users View</span></a></li>

To display an icon with the link

Solution 14 - asp.net Mvc

Do what Mehrdad says - or use the url helper from an HtmlHelper extension method like Stephen Walther describes here and make your own extension method which can be used to render all of your links.

Then it will be easy to render all links as buttons/anchors or whichever you prefer - and, most importantly, you can change your mind later when you find out that you actually prefer some other way of making your links.

Solution 15 - asp.net Mvc

you can create your own extension method
take look at my implementation

public static class HtmlHelperExtensions
{
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt, object htmlAttributesForAnchor, object htmlAttributesForImage)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

        // build the <img> tag
        var imgBuilder = new TagBuilder("img");
        imgBuilder.MergeAttribute("src", url.Content(imagePath));
        imgBuilder.MergeAttribute("alt", alt);
        imgBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributesForImage));
        string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

        // build the <a> tag
        var anchorBuilder = new TagBuilder("a");
        anchorBuilder.MergeAttribute("href", action != null ? url.Action(action, routeValues) : "#");
        anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
        anchorBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributesForAnchor));

        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
        return MvcHtmlString.Create(anchorHtml);
    }
}

then use it in your view take look at my call

 @Html.ActionImage(null, null, "../../Content/img/Button-Delete-icon.png", Resource_en.Delete,
               new{//htmlAttributesForAnchor
                   href = "#",
                   data_toggle = "modal",
                   data_target = "#confirm-delete",
                   data_id = user.ID,
                   data_name = user.Name,
                   data_usertype = user.UserTypeID
               }, new{ style = "margin-top: 24px"}//htmlAttributesForImage
                    )

Solution 16 - asp.net Mvc

For Material Design Lite and MVC:

<a class="mdl-navigation__link" href='@Url.Action("MyAction", "MyController")'>Link Name</a>

Solution 17 - asp.net Mvc

@using (Html.BeginForm("DeleteMember", "Member", new { id = Model.MemberID }))
    {
        <input type="submit" value="Delete Member" onclick = "return confirm('Are you sure you want to delete the member?');" />
    }

Solution 18 - asp.net Mvc

There seems to be lots of solutions on how to created a link that displays as an image, but none that make it appear to be a button.

There is only good way that I have found to do this. Its a little bit hacky, but it works.

What you have to do is create a button and a separate action link. Make the action link invisible using css. When you click on the button, it can fire the click event of the action link.

<input type="button" value="Search" onclick="Search()" />
 @Ajax.ActionLink("Search", "ActionName", null, new AjaxOptions {}, new { id = "SearchLink", style="display:none;" })

function Search(){
    $("#SearchLink").click();
 }

It may be a pain in the butt to do this every time you add a link that needs to look like a button, but it does accomplish the desired result.

Solution 19 - asp.net Mvc

use FORMACTION

<input type="submit" value="Delete" formaction="@Url.Action("Delete", new { id = Model.Id })" />

Solution 20 - asp.net Mvc

Url.Action() will get you the bare URL for most overloads of Html.ActionLink, but I think that the URL-from-lambda functionality is only available through Html.ActionLink so far. Hopefully they'll add a similar overload to Url.Action at some point.

Solution 21 - asp.net Mvc

Just found this extension to do it - simple and effective.

Solution 22 - asp.net Mvc

The way I have done it is to have the actionLink and the image seperately. Set the actionlink image as hidden and then added a jQuery trigger call. This is more of a workaround.

'<%= Html.ActionLink("Button Name", "Index", null, new { @class="yourclassname" }) %>'
<img id="yourImage" src="myImage.jpg" />

Trigger example:

$("#yourImage").click(function () {
  $('.yourclassname').trigger('click');
});

Solution 23 - asp.net Mvc

This is how I did it without scripting:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get))
{
    <button type="submit" 
            class="btn btn-default" 
            title="Action description">Button Label</button>
}

Same, but with parameter and confirmation dialog:

@using (Html.BeginForm("Action", "Controller", 
        new { paramName = paramValue }, 
        FormMethod.Get, 
        new { onsubmit = "return confirm('Are you sure?');" }))
{
    <button type="submit" 
            class="btn btn-default" 
            title="Action description">Button Label</button>
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyan LundyView Question on Stackoverflow
Solution 1 - asp.net MvcjslattsView Answer on Stackoverflow
Solution 2 - asp.net MvcMarkView Answer on Stackoverflow
Solution 3 - asp.net MvcDevDaveView Answer on Stackoverflow
Solution 4 - asp.net MvcagAusView Answer on Stackoverflow
Solution 5 - asp.net MvcCameron ForwardView Answer on Stackoverflow
Solution 6 - asp.net MvcAmir ChatrbahrView Answer on Stackoverflow
Solution 7 - asp.net MvcPatrick KanView Answer on Stackoverflow
Solution 8 - asp.net MvcEmperor 2052View Answer on Stackoverflow
Solution 9 - asp.net MvcmmxView Answer on Stackoverflow
Solution 10 - asp.net MvchauganView Answer on Stackoverflow
Solution 11 - asp.net MvcJiri HWeb HoralekView Answer on Stackoverflow
Solution 12 - asp.net MvcMirkoView Answer on Stackoverflow
Solution 13 - asp.net MvcAndrew DayView Answer on Stackoverflow
Solution 14 - asp.net Mvcmookid8000View Answer on Stackoverflow
Solution 15 - asp.net MvcBasheer AL-MOMANIView Answer on Stackoverflow
Solution 16 - asp.net MvcRody DavisView Answer on Stackoverflow
Solution 17 - asp.net Mvcuser477864View Answer on Stackoverflow
Solution 18 - asp.net MvcbsayeghView Answer on Stackoverflow
Solution 19 - asp.net MvcSergeView Answer on Stackoverflow
Solution 20 - asp.net MvcDhanasekarView Answer on Stackoverflow
Solution 21 - asp.net MvcShaul BehrView Answer on Stackoverflow
Solution 22 - asp.net MvchatsrumandcodeView Answer on Stackoverflow
Solution 23 - asp.net MvcJevgenij MartynenkoView Answer on Stackoverflow