c# - 如何将asp-append-version ="true"实现到background-image属性?

标签 c# html asp.net-core asp.net-core-tag-helpers asp-append-version

我正在尝试实现 HTMLTagHelper asp-append-version="true"到我的图像。 问题是关于 DOM 分布,我没有将属性分配给 <img>标签但到 <div>包含带有 background-url 的图像属性。

此外,div 是在加载所有 DOM 之前生成的,我不知道是否会有不同的方法来执行此操作。

一个很明显,更改 divimg标签,但我不想要它,因为我的设计必须保持不变。

我的 JavaScript 到目前为止是这样的:

cardHTML += '<div asp-append-version="true" class="card littleCard" style="background-image: url(/Content/Img/Especialistas/LittleCard/' + especialista.idEspecialista + '.jpg' + ')' + '" >';
cardHTML += '</div>';

asp-append-version="true"不适用于 div标签。 关于如何找到处理这个问题的方法有什么想法吗?

谢谢

最佳答案

您可以创建自定义 TagHelper 来定位具有内联样式属性的所有元素。我尝试过的以下示例看起来工作正常,但如果您想要更标准的东西(类似于 ImageTagHelper,...),您可以尝试查看基类 UrlResolutionTagHelper 。我不太确定为什么它需要更复杂,基本上你需要在实际处理更多之前解析 URL。我尝试过使用简单的 IFileVersionProvider,它也适用于相对路径(当然解析的路径应该位于当前服务器的 Web 根目录)。

以下简单示例适用于 HtmlString 的属性值(这几乎是常见情况,某些自定义渲染可能会注入(inject)不是 HtmlString 的 IHtmlContent ,对于这种复杂的情况,可以引用 UrlResolutionTagHelper 的源码,甚至复制几乎一模一样的相关代码也可以):

//target only elements having an inline style attribute
[HtmlTargetElement(Attributes = "style")]
public class InlineStyleBackgroundElementTagHelper : TagHelper
{
    readonly IFileVersionProvider _fileVersionProvider;        
    const string BACKGROUND_URL_PATTERN = "(background(?:-image)?\\s*:[^;]*url)(\\([^)]+\\))";
    public InlineStyleBackgroundElementTagHelper(IFileVersionProvider fileVersionProvider)
    {
        _fileVersionProvider = fileVersionProvider;
    }
    //bind the asp-append-version property
    [HtmlAttributeName("asp-append-version")]
    public bool AppendsVersion { get; set; }
    //inject ViewContext from the current request
    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (AppendsVersion)
        {
            if (output.Attributes.TryGetAttribute("style", out var styleAttr))
            {
                //the value here should be an HtmlString, so this basically 
                //gets the raw plain string of the style attribute's value
                var inlineStyle = styleAttr.Value.ToString();
                var basePath = ViewContext.HttpContext.Request.PathBase;
                inlineStyle = Regex.Replace(inlineStyle, BACKGROUND_URL_PATTERN, m =>
                {
                    //extract the background url contained in the inline style
                    var backgroundUrl = m.Groups[2].Value.Trim('(', ')', ' ');
                    //append the version
                    var versionedUrl = _fileVersionProvider.AddFileVersionToPath(basePath, backgroundUrl);

                    //format back the inline style with the versioned url
                    return $"{m.Groups[1]}({versionedUrl})";
                }, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                output.Attributes.SetAttribute("style", inlineStyle);
            }
        }
    }
}

用法:就像在其他内置标记帮助上使用 asp-append-version 一样。 (就像你的例子一样)。

关于c# - 如何将asp-append-version ="true"实现到background-image属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66205924/

相关文章:

javascript - 如何将这两个表与两个模型合并?

c# - TableLayoutPanel 的自动滚动属性不起作用

html - 使用 HTML/CSS 构建模板

c# - 在同一 HTTP 请求 ASP.NET Core C# 中混合异步和同步

c# - .NET Core cookie 身份验证与 AWS Lambda 不持久

C# 使用模式将两个字符串列表相交

c# - 解析器错误消息 : Could not load type : the file of the master page

jquery - HTML 导航栏无法捕捉到浏览器屏幕顶部

html - 使用 flex 垂直和水平居中时从跨度中删除下划线

c# - 使用 XUnit c# 进行功能测试中的类型化配置