2011-11-17 7 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'에 대한 정의가없고 확장 메서드가없는 'ActionLink'오류가 발생합니다. 'System.Web.Mvc.HtmlHelper'유형의 첫 번째 인수를 수락 할 수 있습니다. 추가 할 라이브러리가 있습니까? – Rondel

+0

System.Web.Mvc에 대한 참조를 포함하고 클래스 파일 'using System.Web.Mvc;'에 마지막으로 확장 프로그램의 클래스 파일을 가리키는 확장을 사용하는 위치에 using을 추가해야합니다. –

+0

지금 알 수 있습니다. System.Web.MVC 및 System.Web.Routing을 클래스에 추가했지만 System.Web.Mvc.Html;을 사용하여 추가 할 때까지 작동하지 않습니다. ' 나에게 어떤 의미가 없지만 위대한 작품 – Rondel

관련 문제