// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")
Here is a sample extension method for the code above:
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
Public Module ActionImage
<System.Runtime.CompilerServices.Extension()>
Function ActionImage(html As HtmlHelper, Action As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString
Dim url = New UrlHelper(html.ViewContext.RequestContext)
Dim imgHtml As String
'Build the <img> tag
Dim imgBuilder = New TagBuilder("img")
With imgBuilder
.MergeAttribute("src", url.Content(ImagePath))
.MergeAttribute("alt", AltText)
imgHtml = .ToString(TagRenderMode.Normal)
End With
Dim aHtml As String
'Build the <a> tag
Dim aBuilder = New TagBuilder("a")
With aBuilder
.MergeAttribute("href", url.Action(Action, RouteValues))
.InnerHtml = imgHtml 'Include the <img> tag inside
aHtml = aBuilder.ToString(TagRenderMode.Normal)
End With
Return MvcHtmlString.Create(aHtml)
End Function
<Extension()>
Function ActionImage(html As HtmlHelper, Action As String, Controller As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString
Dim url = New UrlHelper(html.ViewContext.RequestContext)
Dim imgHtml As String
'Build the <img> tag
Dim imgBuilder = New TagBuilder("img")
With imgBuilder
.MergeAttribute("src", url.Content(ImagePath))
.MergeAttribute("alt", AltText)
imgHtml = .ToString(TagRenderMode.Normal)
End With
Dim aHtml As String
'Build the <a> tag
Dim aBuilder = New TagBuilder("a")
With aBuilder
.MergeAttribute("href", url.Action(Action, Controller, RouteValues))
.InnerHtml = imgHtml 'Include the <img> tag inside
aHtml = aBuilder.ToString(TagRenderMode.Normal)
End With
Return MvcHtmlString.Create(aHtml)
End Function
End Module