2009-06-12 62 views

回答

135

剃刀(視圖引擎):

<a href="@Url.Action("ActionName", "ControllerName")"> 
    <img src="@Url.Content("~/Content/img/imgname.jpg")" /> 
</a> 

ASPX(視圖引擎):

<a href="<%= Url.Action("ActionName", "ControllerName") %>"> 
    <img src="<%= Url.Content("~/Content/img/imgname.jpg") %>" /> 
</a> 

顯然,如果你做的比這一次更,寫一個幫手吧。並填寫img/a的其他屬性。但是這應該給你一個總的想法。

22

嘗試是這樣的:

public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName) 
{ 
    var urlHelper = new UrlHelper(html.ViewContext.RequestContext); 

    string imgUrl = urlHelper.Content(imgSrc); 
    TagBuilder imgTagBuilder = new TagBuilder("img"); 
    imgTagBuilder.MergeAttribute("src", imgUrl); 
    string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing); 

    string url = UrlHelper.Action(actionName); 

    TagBuilder tagBuilder = new TagBuilder("a") { 
     InnerHtml = img 
    }; 
    tagBuilder.MergeAttribute("href", url); 

    return tagBuilder.ToString(TagRenderMode.Normal); 
} 

希望這有助於

+6

我建議改變`TagRenderMode.Normal`到`TagRenderMode。SelfClosing`爲img;否則它呈現爲``而不是`` – 2010-02-05 18:45:07

+0

好的建議,謝謝邁克爾 – 2010-02-05 19:39:10

+1

行動不是UrlHelper類的靜態方法,所以它應該從urlHelper對象調用。 – 2014-06-25 12:46:47

0

您可以創建的HtmlHelper可與鏈接返回圖像... 作爲參數,你會傳遞給喜歡的HtmlHelper圖像路徑和鏈接值並在htmlhelper中,您將使用StringBuilder來正確格式化該鏈接圖像的html ...

歡呼聲

2

更容易...

改變你的代碼是:

<p class="site-title">@Html.ActionLink(" ", "Index", "Home", 
    new 
    { 
     style = "background: url('" + Url.Content("~/images/logo.png") + "') no-repeat center right; display:block; height:50px;width:50px;" 
    })</p> 
6

通過@Craig斯頓茨給出的第一個答案是絕對完美的,但我擔心的是,如果你有Ajax.ActionLink而不是Html.ActionLink你會怎麼辦。在這裏我將解釋兩種方法的簡單解決方案。您可以爲Html.ActonLink做如下所示:

@Html.Raw(@Html.ActionLink("[replacetext]", "Index", "Home").ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" ... />")) 

相同的概念可以應用於Ajax.ActionLink

@Html.Raw(@Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" … />")) 

所以這將是您輕鬆。

編輯:

ActionLink的圖像的樣式表或類名稱

隨着樣式表

@Html.Raw(@Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" style=\"width:10%\" ... />")) 

使用類名稱

<style> 
.imgClass { 
width:20% 
} 

@Html.Raw(@Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" class=\"imgClass\" ... />")) 

欲瞭解更多關於參考圖像周圍參觀的ActionLink ActionLink around Image in Asp.net MVC

1

您可以使用url.content:

@Url.Content("~/images/img/slide.png") 

這個回報相對路徑