HTML.ActionLink como botón o imagen, no como enlace


En la última versión (RC1) de ASP.NET MVC, cómo consigo Html.ActionLink para representar como un botón o una imagen en lugar de un enlace?

Author: Ryan Lundy, 2009-02-27

22 answers

Respuesta tardía, pero podría simplemente mantenerlo simple y aplicar una clase CSS al objeto htmlAttributes.

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

Y luego crea una clase en tu hoja de estilos

a.classname
{
    background: url(../Images/image.gif) no-repeat top left;
     display: block;
     width: 150px;
     height: 150px;
     text-indent: -9999px; /* hides the link text */
}
 313
Author: Mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-14 09:29:29

Me gusta usar Url.Action () y Url.Content() como este:

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

Estrictamente hablando, la Url.El contenido solo es necesario para la ruta no es realmente parte de la respuesta a su pregunta.

Gracias a @BrianLegg por señalar que esto debería usar la nueva sintaxis de la vista Razor. El ejemplo se ha actualizado en consecuencia.

 334
Author: jslatts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-21 16:37:52

Tomando prestada la respuesta de Patrick, descubrí que tenía que hacer esto:

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

Para evitar llamar al método post del formulario.

 88
Author: DevDave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-20 13:43:20

Llámame simplista, pero solo lo hago:

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

Y usted acaba de cuidar de la highlight hipervínculo. A nuestros usuarios les encanta:)

 49
Author: agAus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-27 04:29:56

Simplemente:

<button onclick="@Url.Action("index", "Family", new {familyid = Model.FamilyID })">Cancel</button>
 15
Author: Patrick Kan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-28 17:52:45

Una respuesta tardía, pero así es como hago mi ActionLink en un botón. Estamos usando Bootstrap en nuestro proyecto, ya que lo hace conveniente. No importa la @T ya que es solo un traductor que estamos utilizando.

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

Lo anterior da un enlace como este y se ve como la imagen de abajo:

localhost:XXXXX/Firms/AddAffiliation/F0500

botón de demostración de imagen con bootstrap

En mi opinión:

@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>

}

Espero que esto ayude a alguien

 14
Author: Emperor 2052,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-14 09:49:29

Si no desea utilizar un enlace, utilice botón. también puede agregar imagen al botón:

<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" realiza la acción en lugar de enviar el formulario.

 13
Author: Amir Chatrbahr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-02 02:41:04

No puedes hacer esto con Html.ActionLink. Debe usar Url.RouteUrl y usar la URL para construir el elemento que desea.

 12
Author: Mehrdad Afshari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-07 19:08:02

Respuesta incluso posterior, pero me encontré con un problema similar y terminé escribiendo mi propia Enlace de imagen HtmlHelper extensión.

Puedes encontrar una implementación en mi blog en el enlace de arriba.

Se acaba de agregar en caso de que alguien esté buscando una implementación.

 8
Author: Mirko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-15 18:42:31

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

 8
Author: Jiri HWeb Horalek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-05 14:04:29

Usando bootstrap este es el enfoque más corto y limpio para crear un enlace a una acción del controlador que aparece como un botón dinámico:

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

O para usar ayudantes Html:

@Html.ActionLink("Click Me", "Action", "Controller", new { @class = "btn btn-primary" })
 7
Author: Cameron Forward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-31 01:54:48
<li><a href="@Url.Action(  "View", "Controller" )"><i class='fa fa-user'></i><span>Users View</span></a></li>

Para mostrar un icono con el enlace

 5
Author: Andrew Day,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-26 12:35:31

Haga lo que Mehrdad dice - o use el ayudante url de un método de extensión HtmlHelper como Stephen Walther describe aquí y haga su propio método de extensión que se puede usar para renderizar todos sus enlaces.

Entonces será fácil representar todos los enlaces como botones/anclas o lo que prefiera, y, lo más importante, puede cambiar de opinión más tarde cuando descubra que realmente prefiere alguna otra forma de hacer sus enlaces.

 4
Author: mookid8000,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-27 20:25:05

Una forma sencilla de hacer su Html.ActionLink en un botón (siempre y cuando tenga BootStrap conectado - que probablemente tenga) es así:

@Html.ActionLink("Button text", "ActionName", "ControllerName", new { @class = "btn btn-primary" })
 4
Author: haugan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-30 14:46:58

Puede crear su propio método de extensión
echa un vistazo a mi implementación

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);
    }
}

Entonces úsalo en tu vista mira mi llamada

 @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
                    )
 3
Author: Basheer AL-MOMANI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-16 16:39:52
@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?');" />
    }
 1
Author: user477864,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-11 05:07:00

Parece que hay muchas soluciones sobre cómo crear un enlace que se muestre como una imagen, pero ninguna que lo haga parecer un botón.

Solo hay una buena manera que he encontrado para hacer esto. Es un poco raro, pero funciona.

Lo que tienes que hacer es crear un botón y un enlace de acción separado. Haz que el enlace de acción sea invisible usando css. Al hacer clic en el botón, puede disparar el evento de clic del enlace de acción.

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

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

Puede ser un dolor en el trasero hacer esto cada vez que añades un enlace que tiene que parecerse a un botón, pero logra el resultado deseado.

 1
Author: bsayegh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-11 19:35:11

Use FORMACTION

<input type="submit" value="Delete" formaction="@Url.Action("Delete", new { id = Model.Id })" />
 1
Author: Serge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-07 11:25:53

Acaba de encontrar esta extensión para hacerlo - simple y eficaz.

 0
Author: Shaul Behr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-06 12:34:18

La forma en que lo he hecho es tener el ActionLink y la imagen por separado. Establecer la imagen actionlink como oculta y luego se agregó una llamada jQuery trigger. Esto es más una solución alternativa.

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

Ejemplo de disparador:

$("#yourImage").click(function () {
  $('.yourclassname').trigger('click');
});
 0
Author: hatsrumandcode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-03 13:58:53

Url.Action() te dará la URL desnuda para la mayoría de las sobrecargas de Html.ActionLink, pero creo que la funcionalidad URL-from-lambda solo está disponible a través de Html.ActionLink hasta ahora. Esperemos que agreguen una sobrecarga similar a Url.Action en algún momento.

 0
Author: Dhanasekar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-06 03:14:18

Así es como lo hice sin scripting:

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

Igual, pero con parámetro y diálogo de confirmación:

@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>
}
 0
Author: Jevgenij Martynenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-19 22:38:32