Pergunta

No ASP.NET MVC não é um equivalente do Html.ActionLink auxiliar para a tags Img?

Eu tenho um controlador de ação que produz um geradas dinamicamente JPEG e eu queria usar as mesmas expressões Lambda link para ele como eu faço Href usando ActionLink.

Como alternativa, um auxiliar que fornece o URL para uma rota (novamente especificado usando Lambdas) também seria aceitável.

EDITAR:Eu tinha originalmente especificado que eu estava utilizando a pré-Visualização 5, no entanto eu vejo que uma versão Beta foi lançada.Isso tudo-em-tudo que o número de versão foi uma desnecessários pedaço de informações de como eu posso estar atualizando em breve :-)

Foi útil?

Solução

Url.Ação() você irá obter o URL exposto para a maioria das sobrecargas de Html.ActionLink, mas eu acho que o URL-do-lambda funcionalidade só está disponível através de Html.ActionLink até agora.Esperemos que eles vão adicionar um semelhante a sobrecarga Url.Ação em algum ponto.

Outras dicas

Você pode usar a URL.Método de ação

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

Esta questão é antiga, e eu só comecei recentemente com ASP.NET MVC quando o RC já estava fora, mas para quem esta questão mais tarde como eu, isso pode ser interessante:

Pelo menos no RC você pode usar Url.Ação() também com os tipos anônimos, o resultado fica muito mais agradável do que as sugestões acima, eu acho que:

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

Há muitas outras sobrecargas para RouteUrl bem, é claro.

Eu usei uma solução para colocar um marcador em vez de texto para ActionLink e, em seguida, substituí-lo com o meu código de imagem.Algo como isto:

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

Não é a solução mais elegante, mas funciona.

No MVC3, o link ficaria assim:

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

No ASP.NET MVC Beta, você pode usar o Html.BuildUrlFromExpression método de Futuros assembleia (que não está incluído no padrão ASP.NET MVC instalar, mas está disponível a partir CodePlex para criar um link em torno de uma imagem-ou qualquer HTML--usando o lambda-estilo ActionLink sintaxe, como este:

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

Para manter seus links de imagem sem bordas, você precisará adicionar uma regra CSS assim:

img
{
     border: none;
}

Você pode usar esse controle.Ele se comporta como ActionLink.

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

É muito simples para alcançar o MVC 2.Eu criei minha própria muito simples método de extensão de suporte a expressões Lambda para a Url.Auxiliar de acção.Ele requer que você faz referência MVC 2 de Futuros.
Aqui está o 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);
        }
    }
}

Isto é como você usá-lo:

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

Eu sei que o meu post é tarde demais mas eu quero compartilhar :)

Eu adicionado novo método de extensão de algo como isto :

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 este ajudou.

É Url.Conteúdo() o que você está procurando?

Dê a ele algo como Url.Conteúdo("~/path/to/something.jpg") ele irá convertê-lo para o caminho apropriado com base na aplicação de raiz.

-Josh

Eu tirei acima de respostas e fez um pouco de um wrapper de extensão:

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

tornou mais fácil para mim de qualquer maneira, espero que ajude alguém.

Eu tentei colocar a saída do Html.Imagem no meu Html.ImageLink auxiliar.

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

Para mim, o problema é, que o ActionLink nome é codificado de forma que eu tenho < em vez de <.

Apenas removi esta codificação e o resultado funciona para mim.(Será que existe uma maneira melhor de fazer isso ao invés de usar os substituir?)

Adicionando os outros posts:no meu caso (asp.net mvc 3) eu queria o link de uma imagem para agir como um seletor de idiomas por isso, acabei com:

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

A internalização de apoio foi feito através de uma linguagem de rota - fonte original aqui.

Bom soluções aqui, mas se você quiser ter mais do que apenas uma imagem no actionlink?Isto é como eu faço:

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

A desvantagem é que eu ainda tenho que fazer um pouco de estilo no botão-elemento, mas você pode colocar todo o html que você quer lá.

E trabalha com o Ajax helper assim: https://stackoverflow.com/a/19302438/961139

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top