I'm creating a custom helper to create image links as follows:
public static MvcHtmlString ImageLink(this HtmlHelper helper, string imageUrl, string imageAlt, string linkUrl, string linkTitle, string linkTarget)
{
//create the image object
var img = new TagBuilder("img");
//add its attributes
img.MergeAttribute("src", imageUrl);
img.MergeAttribute("alt", imageAlt);
//create the link
var link = new TagBuilder("a");
//add its attributes
link.MergeAttribute("href", linkUrl);
link.MergeAttribute("title", linkTitle);
link.MergeAttribute("target", linkTarget);
//set the inner html of the link to that of the img
link.InnerHtml = img.ToString();
//finally return the link tag
return MvcHtmlString.Create(link.ToString(TagRenderMode.EndTag));
}
But, when I use it, it doesn't render anything at all. When I change the last line to:
return MvcHtmlString.Create(link.ToString(TagRenderMode.SelfClosing));
It only renders the a tag and encapsulates the text just beyond the statement for example:
Hello @Html.ImageLink("...params") world
The result here is that the 'world' text is wrapped in the anchor, but there's no image. I didn't even realise it could do this, since the word 'world' is not part of the helper statement.
I finally changed the final statement to:
return MvcHtmlString.Create(link.ToString(TagRenderMode.Normal));
this worked, but my questions is why? I thought EndTag made more sense especially when looking at the description given by the Intellisense for that option.