ASP.NET Core 部分ビューでクラス属性や一部の属性を転送する

2020/07/04 (更新:2020/11/19)

ASP.NETCore

部分ビュータグヘルパーで、部分ビューに指定された属性を、生成する要素に転送します。
クラス属性は当該部分ビューで個別のクラスを指定するため追加形式で処理します。
サンプルのリポジトリです。
github.com/tassk-work/AspNetCore/tree/master/PartialView02

部分ビュータグヘルパー

[HtmlTargetElement("sample")]
public class SampleTagHelper : PartialTagHelper
{
    private static readonly string[] AttributeTargets = new string[] { "id", "style" };
    public string InnerHtml { get; private set; }
    public string AttributeStr { get; private set; }
    public string AppendClass { get; private set; }

    public SampleTagHelper(
        ICompositeViewEngine viewEngine,
        IViewBufferScope viewBufferScope) : base(viewEngine, viewBufferScope)
    {
        Model = this;
        Name = "_Sample";
    }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        var attributes = output.Attributes.Where(x => AttributeTargets.Contains(x.Name));
        if (attributes.Any())
            AttributeStr = string.Join(" ", attributes.Select(x => $"{x.Name}={x.Value}"));

        var classAttribute = output.Attributes.FirstOrDefault(x => x.Name == "class");
        if (classAttribute != null)
            AppendClass = classAttribute.Value.ToString();

        InnerHtml = (await output.GetChildContentAsync()).GetContent();

        await base.ProcessAsync(context, output);
    }
}
部分ビュー

<div class="sample @Model.AppendClass" @Model.AttributeStr>
    @Html.Raw(Model.InnerHtml)
</div>
ビュー

<div>
    <sample class="sample1" style="color:blue;">
        <p>Sample code</p>
    </sample>
</div>

コメント

コメントはありません。