Wednesday, August 4, 2010

ASP.Net MVC ImageActionLink

The default Html.ActionLink() only takes text, and I like doing icons often to save space for for aesthetics. Here's a simple helper that takes the image url and action as the only required parameters and C# 4.0's fancy new optional parameters for the rest. Doing all the various method overloads for ActionLink sounded like overkill.

/// <summary>
/// Returns an anchor element to the virtual path of the specified action with an image for the content
/// </summary>
/// <param name="html"></param>
/// <param name="imageUrl"></param>
/// <param name="action"></param>
/// <param name="altText"></param>
/// <param name="controllerName"></param>
/// <param name="routeValues"></param>
/// <param name="htmlAttributes"></param>
/// <returns>MvcHtmlString</returns>
public static MvcHtmlString ImageActionLink(
    this HtmlHelper html, 
    string imageUrl, 
    string action, 
    string altText = null, 
    string controllerName = null, 
    object routeValues = null,
    IDictionary<string, object> imageHtmlAttributes = null,
    IDictionary<string, object> htmlAttributes = null)
{
    MvcHtmlString link = html.ActionLink(
        "[replace_me]", 
        action, 
        controllerName, 
        routeValues, 
        htmlAttributes);

    TagBuilder builder = new TagBuilder("img");
    builder.MergeAttributes(imageHtmlAttributes);
    builder.MergeAttribute("src", imageUrl);
    if (altText != null)
        builder.MergeAttribute("alt", altText);
   
    return MvcHtmlString.Create(
        link.ToString().Replace(
            "[replace_me]",
            builder.ToString(TagRenderMode.SelfClosing))
    );
}

No comments:

Post a Comment