【问题标题】:Pick path in Tag Helper attribute在 Tag Helper 属性中选择路径
【发布时间】:2023-03-27 07:28:01
【问题描述】:

假设我想创建一个自定义 ImageTagHelper,它从数据库字段加载图像名称并生成一个 IMG。由于只有名称来自数据库,因此您必须指定一个文件夹,其中所有图像都存在。

标签助手看起来像:

[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);
        }



    }

在 ASP.NET Razor 中我会写:

<image asp-for="Id" image-path="~/images/" alt="No picture" extension="png"/>

image-path-attribute 中输入文本时,如何在 wwwroot 中选择路径?我查看了GitHub ImageTagHelper source code,但src 属性也被定义为字符串。有什么神奇的事情发生了吗?

【问题讨论】:

    标签: c# razor asp.net-core asp.net-core-mvc tag-helpers


    【解决方案1】:

    AFAIK 是用于 HTML 属性的 Visual Studio 工具的魔力。它与标签助手或 aspnet 核心无关。

    【讨论】:

    • 请注意,Razor 存在一个未解决的问题,即在 TagHelpers 上提供标记属性,然后 VS 可以使用该属性来提供适当的 IntelliSense:github.com/aspnet/Razor/issues/429
    猜你喜欢
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多