Is there any way to make an @Html.actionLink an image to click instead of just a hyper link? Currently we have an old that has an onclick attribute linking to a code behind so it needs to be converted to a link that links to the controller, not code behinds which don't exist any more in MVC3.
3 Answers
Is there any way to make an @Html.actionLink an image to click instead of just a hyper link?
No, but you could write a custom HTML helper that generates an image or whatever you like. In fact now tat I think you could apply a CSS class to thins anchor that applies a background-image to it and fixed width and height. I just don't know what you would do with the text => IIRC Html.ActionLink forces you to pass a non-empty linkText parameter as first argument. So finally the custom HTML helper doesn't seem like such a bad idea.
1 Comment
David C
As Dimitrov said, you could write a custom helper for this, but I would only bother with that if you are going to use it alot, if it just to replace one button, I would just use a normal anchor tag and set the href vial @Url.Action() which would point you to a controller/action just like the @Html.ActionLink could do.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
namespace SMART.Infrastructure
{
public static class Html
{
/// <summary>
/// Creates and Action link with a clickable image instead of text.
/// </summary>
/// <param name="helper"></param>
/// <param name="controller">Controller</param>
/// <param name="action">Action</param>
/// <param name="parameters">Parameters</param>
/// <param name="src">Image source</param>
/// <param name="alt">Alternate text(Optional)</param>
/// <returns>An HTML anchor tag with a nested image tag.</returns>
public static MvcHtmlString ActionImage(this HtmlHelper helper, String controller, String action , Object parameters, String src, String alt = "", String title = "")
{
TagBuilder tagBuilder = new TagBuilder("img");
UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
String url = urlHelper.Action(action, controller, parameters);
String imgUrl = urlHelper.Content(src);
String image = "";
StringBuilder html = new StringBuilder();
// build the image tag.
tagBuilder.MergeAttribute("src", imgUrl);
tagBuilder.MergeAttribute("alt", alt);
tagBuilder.MergeAttribute("title", title);
image = tagBuilder.ToString(TagRenderMode.SelfClosing);
html.Append("<a href=\"");
html.Append(url);
html.Append("\">");
html.Append(image);
html.Append("</a>");
return MvcHtmlString.Create(html.ToString());
}
}
}