Ho unito la risposta di Lucas e " ASP.NET MVC Helpers, Merging two object htmlAttributes together " e più controllerName al codice seguente:
// Esempio di utilizzo in CSHTML
@Html.ActionImage("Edit",
"EditController"
new { id = MyId },
"~/Content/Images/Image.bmp",
new { width=108, height=129, alt="Edit" })
E la classe di estensione per il codice sopra:
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
namespace MVC.Extensions
{
public static class MvcHtmlStringExt
{
// Extension method
public static MvcHtmlString ActionImage(
this HtmlHelper html,
string action,
string controllerName,
object routeValues,
string imagePath,
object htmlAttributes)
{
///programming/4896439/action-image-mvc3-razor
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
var dictAttributes = htmlAttributes.ToDictionary();
if (dictAttributes != null)
{
foreach (var attribute in dictAttributes)
{
imgBuilder.MergeAttribute(attribute.Key, attribute.Value.ToString(), true);
}
}
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
public static IDictionary<string, object> ToDictionary(this object data)
{
///programming/6038255/asp-net-mvc-helpers-merging-two-object-htmlattributes-together
if (data == null) return null; // Or throw an ArgumentNullException if you want
BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (PropertyInfo property in
data.GetType().GetProperties(publicAttributes))
{
if (property.CanRead)
{
dictionary.Add(property.Name, property.GetValue(data, null));
}
}
return dictionary;
}
}
}
~/Content
). Il percorso../../Content
può non essere valido da percorsi diversi (ad esempio/
,/Home
,/Home/Index
).