亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

TagHelperOutput 將屬性添加到結尾,而不是開始

TagHelperOutput 將屬性添加到結尾,而不是開始

C#
叮當貓咪 2023-07-09 15:08:46
我注意到 TagHelperOutput Attribute.Add 將文本添加到每個屬性的開頭。如何將其添加到每個屬性的末尾。base.Process(context,?output); output.Attributes.Add("class","test");因此,目前如果現有類是“按鈕”,新類將是“測試按鈕”。我希望它成為 html 樹中所有類的“按鈕測試”這個問題是針對 TagBuilder 的,TagBuilder AddCssClass順序,添加到開頭,如何在末尾添加新類?
查看完整描述

1 回答

?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

您可以在標簽助手中自定義一個CreateOrMergeAttribute方法,并首先將新的 css 類添加到屬性列表中。像下面這樣:


    public class EmailTagHelper: TagHelper

{

    private const string EmailDomain = "contoso.com";


    // Can be passed via <email mail-to="..." />. 

    // PascalCase gets translated into kebab-case.

    public string MailTo { get; set; }


    public override void Process(TagHelperContext context, TagHelperOutput output)

    {

        output.TagName = "a";    // Replaces <email> with <a> tag


        var address = MailTo + "@" + EmailDomain;


        output.Attributes.SetAttribute("href", "mailto:" + address);

        output.Content.SetContent(address);


        CreateOrMergeAttribute("class", "test", output);

    }


    private void CreateOrMergeAttribute(string name, object content, TagHelperOutput output)

    {

        var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == name);

        if (currentAttribute == null)

        {

            var attribute = new TagHelperAttribute(name, content);

            output.Attributes.Add(attribute);

        }

        else

        {

            var newAttribute = new TagHelperAttribute(

                name,

                $"{currentAttribute.Value.ToString()} {content.ToString()}",

                currentAttribute.ValueStyle);

            output.Attributes.Remove(currentAttribute);

            output.Attributes.Add(newAttribute);

        }

    }

}

結果截圖:

http://img1.sycdn.imooc.com//64aa5d2200011fe005400028.jpg

查看完整回答
反對 回復 2023-07-09
  • 1 回答
  • 0 關注
  • 126 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號