In questo post, invece, vedremo come creare un helper simile ma che usa delle immagini "normali" al posto dei bootstrap glyphs.
/// <summary>
/// Create an ActionLink with an associated image
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="linkText"></param>
/// <param name="actionName"></param>
/// <param name="controllerName"></param>
/// <param name="imagePath"></param>
/// <param name="routeValues"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcHtmlString ImageImgActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string imagePath, object routeValues = null, object htmlAttributes = null)
{
//Exemple of result:
//<a href="@Url.Action("Edit", new { id = Model.id_rod })">
// <i class="glyphicon glyphicon-pencil"></i>
// <span>Edit</span>
//</a>
if (imagePath.StartsWith("~/"))
{
imagePath = VirtualPathUtility.ToAbsolute(imagePath);
}
var builderImage = new TagBuilder("image");
builderImage.MergeAttribute("src", imagePath);
builderImage.MergeAttribute("alt", linkText);
builderImage.MergeAttribute("style", "border=0");
string imageTag = builderImage.ToString(TagRenderMode.SelfClosing);
string spanTag = "";
if (!string.IsNullOrEmpty(linkText))
{
var builderSPAN = new TagBuilder("span");
builderSPAN.InnerHtml = " " + linkText;
spanTag = builderSPAN.ToString(TagRenderMode.Normal);
}
//Create the "a" tag that wraps
var builderA = new TagBuilder("a");
var requestContext = HttpContext.Current.Request.RequestContext;
var uh = new UrlHelper(requestContext);
builderA.MergeAttribute("href", uh.Action(actionName, controllerName, routeValues));
if (htmlAttributes != null)
{
IDictionary<string, object> attributes = new RouteValueDictionary(htmlAttributes);
builderA.MergeAttributes(attributes);
}
builderA.InnerHtml = imageTag + spanTag;
return new MvcHtmlString(builderA.ToString(TagRenderMode.Normal));
}
È possibile passare all'helper sia url relativi che assoluti (parametro imagePath) in modo da avere la massima flessibilità.
Nessun commento:
Posta un commento