2010-09-14 12 views
7

jest prosty html:jak zrobić Html.ActionLink bez tekstu, ale z obrazem wewnątrz

<%-- 
<a href="?language=de"> 
    <img src="/Images/Company/de.png" alt="Webseite auf Deutsch" style="border: 0;" /> 
</a> 
--%> 

chciałbym uczynić z nich Html.ActionLink:

<%= Html.ActionLink("", "ChangeCulture", "Account", new { lang = "de", returnUrl = this.Request.RawUrl }, new { @style = "background-image: url(/Images/Company/de.png)", @class = "languageLink" }) %> 

chciałbym mieć mój link bez tekstu. nie działa, null w pierwszym parametrze jest niedozwolony. obraz jest krótki jak zwykle. jak mogę użyć html.actionlink bez tekstu, ale z obrazem?

+0

możliwy duplikat [odpowiednik obrazu ActionLink w ASP.NET MVC] (http://stackoverflow.com/questions/210711/image-equivalent-of-actionlink-in-asp-net-mvc) – flq

Odpowiedz

10

Oto rozwiązanie.

<a href="<%= Url.RouteUrl("MyRoute", new { id = Model.Id }) %>"> 
    <img src="myimage.png" alt="My Image" />. 
</a> 

Zasadniczo actionlink jest dla linków tekstowych i nie jest odpowiednikiem dla obrazów, ale można użyć Url.RouteUrl aby uzyskać adres link i umieścić dowolny kod HTML chcesz wewnątrz kotwicy (Oczywiście W3C).

3

oparciu o poprzednie SO pytanie (które było zamknięte), oto rozwiązanie:

public static string ImageLink(this HtmlHelper htmlHelper, 
    string imgSrc, string alt, 
    string actionName, string controllerName, object routeValues, 
    object htmlAttributes, object imgHtmlAttributes) 
{ 
    UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url; 
    string imgtag = htmlHelper.Image(imgSrc, alt, imgHtmlAttributes); 
    string url = urlHelper.Action(actionName, controllerName, routeValues); 

    TagBuilder imglink = new TagBuilder("a"); 
    imglink.MergeAttribute("href", url); 
    imglink.InnerHtml = imgtag; 
    imglink.MergeAttributes(new RouteValueDictionary(htmlAttributes), true); 

    return imglink.ToString(); 
} 

orignal można znaleźć tutaj: Is there an ASP.NET MVC HtmlHelper for image links?

6

ten sposób jest najłatwiejszy (używając Razor):

<a href="@Url.Action("Action", "Controller", new { lang = "de", returnUrl = this.Request.RawUrl }, new { @style = "background-image: url(/Images/Company/de.png)", @class = "languageLink" })"><img src="myimage.png" alt="My Image" /></a> 
+0

Nie ma htmlAt Argument tribute w metodzie @ Url.Action. Powinien to być @ Url.Action (string nazwa_działania, ciąg kontroler nazwa, RouteValueDictionary routeValues) – Finickyflame

Powiązane problemy