Pregunta

En ASP.NET MVC, ¿existe un equivalente del asistente Html.ActionLink para etiquetas Img?

Tengo una acción de controlador que genera un JPEG generado dinámicamente y quería usar las mismas expresiones Lambda para vincularlo que hago con HREF usando ActionLink.

Alternativamente, también sería aceptable un asistente que simplemente proporcione la URL de una ruta (nuevamente especificada usando Lambdas).

EDITAR:Originalmente había especificado que estaba usando la Vista previa 5, sin embargo, veo que se lanzó una versión Beta.Entonces, en general, el número de versión era una información innecesaria, ya que es posible que actualice pronto :-)

¿Fue útil?

Solución

Url.Action() le proporcionará la URL básica para la mayoría de las sobrecargas de Html.ActionLink, pero creo que la funcionalidad URL desde lambda solo está disponible a través de Html.ActionLink hasta ahora.Con suerte, agregarán una sobrecarga similar a Url.Action en algún momento.

Otros consejos

Puedes usar el método URL.Action

<a href="<%= Url.Action("Create")  %>"><img src="../../Content/Images/add_48.png" /></a>

Esta pregunta es anterior y comencé recientemente con ASP.NET MVC cuando el RC ya estaba disponible, pero para aquellos que encuentren esta pregunta más tarde, como yo, esto podría ser interesante:

Al menos en RC puedes usar Url.Action() también con tipos anónimos, el resultado se ve mucho mejor que las sugerencias anteriores, supongo:

<a href="<%= Url.RouteUrl("MyRoute", new { param1 = "bla", param2 = 5 }) %>">
   put in <span>whatever</span> you want, also <img src="a.gif" alt="images" />.
</a>

Por supuesto, también existen muchas otras sobrecargas para RouteUrl.

Utilicé una solución alternativa para colocar un marcador en lugar de texto para ActionLink y luego reemplazarlo con mi código de imagen.Algo como esto:

<%= Html.ActionLink("__IMAGE_PLACEHOLDER__", "Products").Replace("__IMAGE_PLACEHOLDER__", "<img src=\"" + myImgUrl + "\" />")%>

No es la solución más elegante pero funciona.

En MVC3, su enlace se vería así:

<a href="@Url.Action("Create")"><img src="../../Content/Images/add_48.png" /></a>

En ASP.NET MVC Beta, puede utilizar el Html.BuildUrlFromExpression método en el ensamblado Futures (que no está incluido en la instalación predeterminada de ASP.NET MVC, pero está disponible en CódigoPlex) para crear un vínculo alrededor de una imagen (o cualquier HTML) utilizando la sintaxis ActionLink estilo lambda, como esta:

<a href="<%=Html.BuildUrlFromExpression<MyController>(c => c.MyAction())%>">
     <%=Html.Image("~/Content/MyImage.gif")%>
</a>

Para mantener los enlaces de sus imágenes sin bordes, deberá agregar una regla CSS como esta:

img
{
     border: none;
}

Puede utilizar este control. Se comporta como ActionLink.

http://agilefutures.com/index.php/2009/06/actionimage-aspnet-mvc

Es bastante sencillo de lograr en MVC 2.He creado mi propio método de extensión muy simple para admitir expresiones Lambda para el asistente Url.Action.Requiere que haga referencia a MVC 2 Futures.
Aquí está el código:

using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Routing;

using ExpressionHelperInternal=Microsoft.Web.Mvc.Internal.ExpressionHelper;

namespace Bnv.Bssi.Web.Infrastructure.Helpers
{
    public static class UrlExtensions
    {
        public static string Action<TController>(this UrlHelper helper, Expression<Action<TController>> action) where TController : Controller
        {
            RouteValueDictionary routeValuesFromExpression = ExpressionHelperInternal.GetRouteValuesFromExpression<TController>(action);

            return helper.Action(routeValuesFromExpression["action"].ToString(), routeValuesFromExpression);
        }
    }
}

Así es como lo usas:

<img src="<%= Url.Action<YourController>(c => c.YourActionMethod(param1, param2)); %>" />

Sé que mi publicación es demasiado tarde pero quiero compartirla :)

Agregué un nuevo método de extensión similar a este:

public static class ImageExtensions
{
    public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string additionalText = null, string actionName = null, string controllerName = null, object routeValues = null, object linkHtmlAttributes = null, object imgHtmlAttributes = null)
    {
        var urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
        var url = "#";
        if (!string.IsNullOrEmpty(actionName))
            url = urlHelper.Action(actionName, controllerName, routeValues);

        var imglink = new TagBuilder("a");
        imglink.MergeAttribute("href", url);
        imglink.InnerHtml = htmlHelper.Image(imgSrc, imgHtmlAttributes) + " " + additionalText;
        linkHtmlAttributes = new RouteValueDictionary(linkHtmlAttributes);
        imglink.MergeAttributes((IDictionary<string, object>)linkHtmlAttributes, true);

        return MvcHtmlString.Create(imglink.ToString());
    }

    public static MvcHtmlString Image(this HtmlHelper htmlHelper, string imgSrc, object imgHtmlAttributes = null)
    {
        var imgTag = new TagBuilder("img");
        imgTag.MergeAttribute("src", imgSrc);
        if (imgHtmlAttributes != null)
        {
            imgHtmlAttributes = new RouteValueDictionary(imgHtmlAttributes);
            imgTag.MergeAttributes((IDictionary<string, object>)imgHtmlAttributes, true);
        }
        return MvcHtmlString.Create(imgTag.ToString());
    }
}

Espero que esto haya ayudado.

¿Es Url.Content() lo que estás buscando?

Déle algo como Url.Content("~/path/to/something.jpg") y lo convertirá en la ruta adecuada según la raíz de la aplicación.

-josh

Tomé las respuestas anteriores e hice una especie de extensión contenedora:

    public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName)
        {
            return ActionImageLink(helper, src, altText, url, actionName, controllerName, null, null);
        }

        public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName, Dictionary<string, string> linkAttributes, Dictionary<string, string> imageAttributes)
        {
            return ActionImageLink(helper, src, altText, url, actionName, controllerName, null, linkAttributes, imageAttributes);
        }

        public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName, dynamic routeValues, Dictionary<string, string> linkAttributes, Dictionary<string, string> imageAttributes)
        {
            var linkBuilder = new TagBuilder("a");
            linkBuilder.MergeAttribute("href", routeValues == null ? url.Action(actionName, controllerName) : url.Action(actionName, controllerName, routeValues));

            var imageBuilder = new TagBuilder("img");
            imageBuilder.MergeAttribute("src", url.Content(src));
            imageBuilder.MergeAttribute("alt", altText);

            if (linkAttributes != null)
            {
                foreach (KeyValuePair<string, string> attribute in linkAttributes)
                {
                    if (!string.IsNullOrWhiteSpace(attribute.Key) && !string.IsNullOrWhiteSpace(attribute.Value))
                    {
                        linkBuilder.MergeAttribute(attribute.Key, attribute.Value);
                    }
                }
            }

            if (imageAttributes != null)
            {
                foreach (KeyValuePair<string, string> attribute in imageAttributes)
                {
                    if (!string.IsNullOrWhiteSpace(attribute.Key) && !string.IsNullOrWhiteSpace(attribute.Value))
                    {
                        imageBuilder.MergeAttribute(attribute.Key, attribute.Value);
                    }
                }
            }

            linkBuilder.InnerHtml = MvcHtmlString.Create(imageBuilder.ToString(TagRenderMode.SelfClosing)).ToString();
            return MvcHtmlString.Create(linkBuilder.ToString());
        }

Me lo ha hecho más fácil de todos modos, espero que ayude a alguien más.

Intenté poner la salida del HTML.Imagen en mi Html.ImageEnlace ayudante.

@(new HtmlString(Html.ActionLink(Html.Image("image.gif").ToString(), "myAction", "MyController").ToString().Replace("&lt;", "<").Replace("&gt;", ">")))

El problema para mí es que el nombre de ActionLink está codificado, por lo que tengo &lt en lugar de <.

Acabo de eliminar esta codificación y el resultado me funciona.(¿Existe una mejor manera de hacer esto en lugar de usar reemplazar?)

Agregando a las otras publicaciones:en mi caso (asp.net mvc 3) quería que un enlace de imagen actuara como selector de idioma, así que terminé con:

  public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string cultureName, object htmlAttributes, object imgHtmlAttributes, string languageRouteName = "lang", bool strictSelected = false)
        {
           UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
           TagBuilder imgTag = new TagBuilder("img");
           imgTag.MergeAttribute("src", imgSrc);
           imgTag.MergeAttributes((IDictionary<string, string>)imgHtmlAttributes, true);

           var language = htmlHelper.LanguageUrl(cultureName, languageRouteName, strictSelected);                      
           string url = language.Url;

           TagBuilder imglink = new TagBuilder("a");
           imglink.MergeAttribute("href", url);
           imglink.InnerHtml = imgTag.ToString();
           imglink.MergeAttributes((IDictionary<string, string>)htmlAttributes, true);

           //if the current page already contains the language parameter make sure the corresponding html element is marked
           string currentLanguage = htmlHelper.ViewContext.RouteData.GetRequiredString("lang");
           if (cultureName.Equals(currentLanguage, StringComparison.InvariantCultureIgnoreCase))
           {
              imglink.AddCssClass("selectedLanguage");
           }
           return new MvcHtmlString(imglink.ToString());
        }

El apoyo a la internalización se realizó a través de una ruta lingüística - fuente original aquí.

Buenas soluciones aquí, pero ¿qué pasa si quieres tener más que solo una imagen en el enlace de acción?Así es como lo hago:

     @using (Html.BeginForm("Action", "Controler", ajaxOptions))
     { 
        <button type="submit">
           <img src="image.png" />            
        </button>
     }

El inconveniente es que todavía tengo que darle un poco de estilo al elemento del botón, pero puedes poner todo el HTML que quieras allí.

Y también funciona con el ayudante de Ajax: https://stackoverflow.com/a/19302438/961139

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top