/// <summary> /// Renders an icon image using the specified metadata. /// </summary> /// <param name="title">The title to use. If NULL, defaults to the value stored on the icon.</param> /// <param name="alt">The alt text. If NULL, defaults to the value stored on the icon.</param> /// <param name="url">A URL to link to. If not NULL, a link tag to this value is wrapped around the icon.</param> /// <param name="onclick">The onclick handler to render.</param> /// <param name="cssClass">The CSS class to assign to the image.</param> /// <param name="attributes">A dictionary of additional html attributes to render.</param> public static IHtmlString Icon(this HtmlHelper html, IIconMetaData icon, string title = null, string alt = null, string url = null, string onclick = null, string cssClass = null, object attributes = null) { var image = new TagBuilder("img"); image.Attributes.Add("alt", alt ?? icon.AltText); image.Attributes.Add("title", title ?? icon.Title); SetOnclickHandler(onclick, image); SetCssClass(cssClass, image); SetImageSrc(html, icon, image); MergeHtmlAttributes(attributes, image); var imageTagHtml = new HtmlString( image.ToString(TagRenderMode.SelfClosing) ); if (url.IsNotNullOrEmpty()) { imageTagHtml = new HtmlString( String.Format("<a href=\"{0}\">{1}</a>", url, imageTagHtml.ToString()) ); } return imageTagHtml; }
private static void SetImageSrc(HtmlHelper html, IIconMetaData icon, TagBuilder image) { var imagePath = icon.Filename; // filenames starting with a "~" are treated as relative to app root if (imagePath.StartsWith("~/")) { var pathWithoutTilde = imagePath.Substring(2); var appRoot = html.ViewContext.HttpContext.Request.ApplicationPath; imagePath = Path.Combine(appRoot, pathWithoutTilde); } image.Attributes.Add("src", imagePath); }