基于 ASP.NETCore 中模型的计数器自定义 tagHelper

Custom tagHelper based on counter from model in ASP.NETCore

我想根据模型中的计数器 属性 呈现不同的文本。

int counter = 8;

我需要自定义 TagHelper:

//pseudo code
  if(counter > 8)
  {
    return "Foo"
  }
  else
  {
    return "Bar"
  }

View 应该喜欢:

<li>
    condition-counter="@counter" //it should generate "Foo", or "Bar" depending on given counter
</li>

您可以按照以下步骤编写自定义标签助手:

1.MyContentTagHelper.cs

[HtmlTargetElement("my-content")]
public class MyContentTagHelper:TagHelper
{
    public int Counter { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        //output.TagName = "span";    // Replaces <my-content> with <span> tag

       if(Counter > 8)
        {
            output.Content.SetContent("Foo");
        }
        else
        {
            output.Content.SetContent("Bar");
        }       

    }
}

2.View:

<li>
    <my-content counter="@counter" ></my-content>
</li>

3.Remember 将 addTagHelper 指令添加到 Views/_ViewImports.cshtml 文件:

@using MyApp
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MyApp

参考https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring?view=aspnetcore-3.1