Imagen de acción MVC3 Razor


119

¿Cuál es la mejor manera de reemplazar enlaces con imágenes usando Razor en MVC3? Simplemente estoy haciendo esto en este momento:

<a href="@Url.Action("Edit", new { id=MyId })"><img src="../../Content/Images/Image.bmp", alt="Edit" /></a> 

¿Existe una forma mejor?


15
No está directamente relacionado, pero le sugiero que utilice archivos PNG o JPG (según el contenido de la imagen) en lugar de archivos BMP. Y como sugirió @jgauffin, también intente usar rutas relativas de la aplicación ( ~/Content). El camino ../../Contentpodría no ser válido a partir de diferentes rutas (por ejemplo /, /Home, /Home/Index).
Lucas

Gracias Lucas. Yo uso png pero el consejo para usar URL.Content es lo que estaba buscando. vote a favor :)
davy

Respuestas:


217

Puede crear un método de extensión para HtmlHelper para simplificar el código en su archivo CSHTML. Puede reemplazar sus etiquetas con un método como este:

// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")

Aquí hay un método de extensión de muestra para el código anterior:

// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
    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);
    string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

    // build the <a> tag
    var anchorBuilder = new TagBuilder("a");
    anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(anchorHtml);
}

5
Excelente fragmento. Cualquiera que quiera usar esto con T4MVC sólo tiene que cambiar el tipo de routeValuesa ActionResulty luego en el url.Actioncambio de función routeValuesderouteValues.GetRouteValueDictionary()
JConstantine

12
@Kasper Skov: coloque el método en una clase estática, luego haga referencia al espacio de nombres de esa clase en Web.config en el /configuration/system.web/pages/namespaceselemento.
Umar Farooq Khawaja

4
¡Bien !, en lugar de alt, acepto un objeto para recibir propiedades html usando un objeto anónimo entonces var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);y finalmenteforeach (var attr in attributes){ imgBuilder.MergeAttribute(attr.Key, attr.Value.ToString());}
guzart

7
No pude hacer que esto funcionara hasta que me di cuenta de que debido a que estoy usando Áreas, se debe agregar una referencia al espacio de nombres de la clase (como lo señaló Umar) a TODOS los archivos web.config en la carpeta Vistas para todas las Áreas, así como la /Viewscarpeta de nivel superior
Mark_Gibson

2
Si solo necesita esto en una sola página, en lugar de cambiar los archivos Web.config, puede agregar una declaración @using en .cshtml y hacer referencia al espacio de nombres
JML

64

Puede usar el Url.Contentque funciona para todos los enlaces, ya que traduce la tilde ~al uri raíz.

<a href="@Url.Action("Edit", new { id=MyId })">
    <img src="@Url.Content("~/Content/Images/Image.bmp")", alt="Edit" />
</a>

3
Esto funciona muy bien en MVC3. ¡Gracias! <a href="@Url.Action("Index","Home")"><img src="@Url.Content("~/Content/images/myimage.gif")" alt="Home" /></a>
rk1962

24

Sobre la base de la respuesta de Lucas anterior, esta es una sobrecarga que toma un nombre de controlador como parámetro, similar a ActionLink. Utilice esta sobrecarga cuando su imagen se vincule a una acción en un controlador diferente.

// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, string controllerName, object routeValues, string imagePath, string alt)
{
    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);
    string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

    // build the <a> tag
    var anchorBuilder = new TagBuilder("a");

    anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(anchorHtml);
}

1
no hay comentarios sobre su agregar aquí ... bueno, digo una buena modificación al código dado. +1 de mi parte.
Zack Jannsen

11

Bueno, podrías usar la solución @Lucas, pero también hay otra forma.

 @Html.ActionLink("Update", "Update", *Your object value*, new { @class = "imgLink"})

Ahora, agregue esta clase en un archivo CSS o en su página:

.imgLink
{
  background: url(YourImage.png) no-repeat;
}

Con esa clase, cualquier enlace tendrá tu imagen deseada.


2
@KasperSkov Olvidé este pequeño problema. Por alguna razón, esta anulación particular del asistente actionLink no funciona con el ejemplo anterior. Tienes el ControllerNamede tu acción. Así:@Html.ActionLink("Update", "Update", "*Your Controller*",*object values*, new {@class = "imgLink"})
AdrianoRR

3

Este resultó ser un hilo muy útil.

Para aquellos que son alérgicos a las llaves, aquí está la versión VB.NET de las respuestas de Lucas y Crake:

Public Module ActionImage
    <System.Runtime.CompilerServices.Extension()>
    Function ActionImage(html As HtmlHelper, Action As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString

        Dim url = New UrlHelper(html.ViewContext.RequestContext)

        Dim imgHtml As String
        'Build the <img> tag
        Dim imgBuilder = New TagBuilder("img")
        With imgBuilder
            .MergeAttribute("src", url.Content(ImagePath))
            .MergeAttribute("alt", AltText)
            imgHtml = .ToString(TagRenderMode.Normal)
        End With

        Dim aHtml As String
        'Build the <a> tag
        Dim aBuilder = New TagBuilder("a")
        With aBuilder
            .MergeAttribute("href", url.Action(Action, RouteValues))
            .InnerHtml = imgHtml 'Include the <img> tag inside
            aHtml = aBuilder.ToString(TagRenderMode.Normal)
        End With

        Return MvcHtmlString.Create(aHtml)

    End Function

    <Extension()>
    Function ActionImage(html As HtmlHelper, Action As String, Controller As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString

        Dim url = New UrlHelper(html.ViewContext.RequestContext)

        Dim imgHtml As String
        'Build the <img> tag
        Dim imgBuilder = New TagBuilder("img")
        With imgBuilder
            .MergeAttribute("src", url.Content(ImagePath))
            .MergeAttribute("alt", AltText)
            imgHtml = .ToString(TagRenderMode.Normal)
        End With

        Dim aHtml As String
        'Build the <a> tag
        Dim aBuilder = New TagBuilder("a")
        With aBuilder
            .MergeAttribute("href", url.Action(Action, Controller, RouteValues))
            .InnerHtml = imgHtml 'Include the <img> tag inside
            aHtml = aBuilder.ToString(TagRenderMode.Normal)
        End With

        Return MvcHtmlString.Create(aHtml)

    End Function

End Module

1

Este método de extensión también funciona (para colocarlo en una clase estática pública):

    public static MvcHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, object routeValues, AjaxOptions ajaxOptions)
    {
        var builder = new TagBuilder("img");
        builder.MergeAttribute("src", imageUrl);
        builder.MergeAttribute("alt", altText);
        var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
        return new MvcHtmlString( link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing)) );
    }

1

Para agregar a todo el trabajo impresionante iniciado por Luke, estoy publicando uno más que toma un valor de clase css y trata a class y alt como parámetros opcionales (válido bajo ASP.NET 3.5+). Esto permitirá una mayor funcionalidad pero reducirá la cantidad de métodos sobrecargados necesarios.

// Extension method
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action,
        string controllerName, object routeValues, string imagePath, string alt = null, string cssClass = null)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

        // build the <img> tag
        var imgBuilder = new TagBuilder("img");
        imgBuilder.MergeAttribute("src", url.Content(imagePath));
        if(alt != null)
            imgBuilder.MergeAttribute("alt", alt);
        if (cssClass != null)
            imgBuilder.MergeAttribute("class", cssClass);

        string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

        // build the <a> tag
        var anchorBuilder = new TagBuilder("a");

        anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
        anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return MvcHtmlString.Create(anchorHtml);
    }

Además, para cualquier persona nueva en MVC, una sugerencia útil: el valor de routeValue debe ser @ RouteTable.Routes ["Inicio"] o lo que sea que su identificación de "ruta" esté en la RouteTable.
Zack Jannsen

1

modificación de diapositiva cambiado Ayudante

     public static IHtmlString ActionImageLink(this HtmlHelper html, string action, object routeValues, string styleClass, string alt)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);
        var anchorBuilder = new TagBuilder("a");
        anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
        anchorBuilder.AddCssClass(styleClass);
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return new HtmlString(anchorHtml);
    }

Clase CSS

.Edit {
       background: url('../images/edit.png') no-repeat right;
       display: inline-block;
       height: 16px;
       width: 16px;
      }

Crea el enlace solo pasa el nombre de la clase

     @Html.ActionImageLink("Edit", new { id = item.ID }, "Edit" , "Edit") 

0

Me uní a la respuesta de Lucas y " ASP.NET MVC Helpers, Fusionando dos objetos htmlAttributes juntos " y más controllerName al siguiente código:

// Uso de muestra en CSHTML

 @Html.ActionImage("Edit",
       "EditController"
        new { id = MyId },
       "~/Content/Images/Image.bmp",
       new { width=108, height=129, alt="Edit" })

Y la clase de extensión para el código anterior:

using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;

namespace MVC.Extensions
{
    public static class MvcHtmlStringExt
    {
        // Extension method
        public static MvcHtmlString ActionImage(
          this HtmlHelper html,
          string action,
          string controllerName,
          object routeValues,
          string imagePath,
          object htmlAttributes)
        {
            ///programming/4896439/action-image-mvc3-razor
            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));

            var dictAttributes = htmlAttributes.ToDictionary();

            if (dictAttributes != null)
            {
                foreach (var attribute in dictAttributes)
                {
                    imgBuilder.MergeAttribute(attribute.Key, attribute.Value.ToString(), true);
                }
            }                        

            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside            
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
        }

        public static IDictionary<string, object> ToDictionary(this object data)
        {
            ///programming/6038255/asp-net-mvc-helpers-merging-two-object-htmlattributes-together

            if (data == null) return null; // Or throw an ArgumentNullException if you want

            BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
            Dictionary<string, object> dictionary = new Dictionary<string, object>();

            foreach (PropertyInfo property in
                     data.GetType().GetProperties(publicAttributes))
            {
                if (property.CanRead)
                {
                    dictionary.Add(property.Name, property.GetValue(data, null));
                }
            }
            return dictionary;
        }
    }
}

0

Esto funcionaría muy bien

<a href="<%:Url.Action("Edit","Account",new {  id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.