Lets say I want to create a custom ImageTagHelper, which loads the image name from a database field and generates an IMG. As there is only the name coming from the db, you have to specify a folder, where all images exist.
The Tag Helper looks like:
[HtmlTargetElement("image", Attributes = ForAttributeName, TagStructure = TagStructure.WithoutEndTag)]
public class ImageTagHelper : Microsoft.AspNetCore.Razor.TagHelpers.TagHelper
{
public ImageTagHelper(IHtmlGenerator generator)
{
}
public ModelExpression For { get; set; }
/// <summary>
/// Path to picture
/// </summary>
public string ImagePath { get; set; }
/// <summary>
/// Extension
/// </summary>
public string Extension { get; set; }
/// <summary>
/// Alt text
/// </summary>
public string Alt { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "img";
output.TagMode = TagMode.SelfClosing;
var src = ImagePath + For.ModelExplorer.Model + "." + Extension;
output.Attributes.Add("src", src);
output.Attributes.Add("alt", Alt);
}
}
In ASP.NET Razor i would write:
<image asp-for="Id" image-path="~/images/" alt="No picture" extension="png"/>
How can I pick a path in wwwroot, when typing text in the image-path-attribute
? I looked in GitHub ImageTagHelper source code, but the src
attribute is also defined as string. Is there something magic happening?
AFAIK that is the magic of visual studio tooling for HTML attributes. It has nothing to do with tag helpers or aspnet core.