I am trying to create a TagHelper that checks for the presence of an image, and if it does not replace the default image path.
Unfortunately, I have problems displaying the "~" character in my tag helper.
For instance. My image src contains "~ \ images \ image1.png". Now I want to check the existence of this file and, if not replace it with another, from the tag attribute. I am stuck matching "~" with wwwroot of my application.
Here is what I actually do:
[HtmlTargetElement("img", TagStructure = TagStructure.WithoutEndTag)]
public class ImageTagHelper : TagHelper
{
public ImageTagHelper(IHostingEnvironment environment)
{
this._env = environment;
}
private IHostingEnvironment _env;
public string DefaultImageSrc { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
string imgPath = context.AllAttributes["src"].Value.ToString();
if (!File.Exists(_env.WebRootPath + imgPath)) {
output.Attributes.SetAttribute("src", _env.WebRootPath + DefaultImageSrc);
}
}
}
source
share