2011-11-17 43 views
4

這可能是一個非常簡單的問題。如何將圖像添加到Html.ActionLink鏈接?在常規HTML我只想把這樣的事情:如何使圖像成爲我的html.ActionLink的一部分?

<a href="url"><img src="whatever.jpg" />Words and Stuff too </a> 

如何能夠將生成的鏈接標籤內的形象呢?

@Html.ActionLink("Change Database Connection","Index","Home",null,null) 

我試着這樣做

@Html.ActionLink("<img src=\"../../Content/themes/base/images/web_database.png\" />Change Database Connection","Index","Home",null,null) 

顯然,這並沒有工作。它只是顯示我img標籤以純文本格式。什麼是實現這一目標的正確方法?我需要一個幫手類這麼簡單嗎?

回答

4

這裏有兩個我已經採用和更新的擴展。

public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string imageUrl, string altText, string actionName, string controller, object routeValues, string _imageClass = "", object htmlAttributes = null) 
{ 
    var image = new TagBuilder("img"); 
    image.MergeAttribute("src", imageUrl); 
    image.MergeAttribute("alt", altText); 
    if (string.IsNullOrEmpty(_imageClass) == false) image.MergeAttribute("class", _imageClass); 
    var link = helper.ActionLink("[replaceme]", actionName, controller, routeValues, htmlAttributes); 
    return new MvcHtmlString(link.ToHtmlString().Replace("[replaceme]", image.ToString(TagRenderMode.SelfClosing))); 
} 

public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string imageUrl, string altText, RouteValueDictionary routeValues, string _imageClass = "", object htmlAttributes = null) 
{ 
    var image = new TagBuilder("img"); 
    image.MergeAttribute("src", imageUrl); 
    image.MergeAttribute("alt", altText); 
    if (string.IsNullOrEmpty(_imageClass) == false) image.MergeAttribute("class", _imageClass); 
    var link = helper.ActionLink("[replaceme]", routeValues, htmlAttributes); 
    return new MvcHtmlString(link.ToHtmlString().Replace("[replaceme]", image.ToString(TagRenderMode.SelfClosing))); 
} 
+0

出於某種原因,它不會與'helper.ActionLink'編譯。我收到一個錯誤'System.Web.Mvc.HtmlHelper'沒有包含'ActionLink'的定義,也沒有找到接受類型'System.Web.Mvc.HtmlHelper'的第一個參數的擴展方法'ActionLink'。我需要添加一個庫嗎? – Rondel

+0

您需要包含對System.Web.Mvc的引用並添加到類文件'using System.Web.Mvc;'中,最後,將using添加到指向擴展的類文件的擴展名的位置。 –

+0

現在明白了。我將System.Web.MVC和System.Web.Routing添加到了我的課程中,但直到我添加'using System.Web.Mvc.Html;'後才能工作。對我沒有任何意義,但很有效 – Rondel

相關問題