TagHelper 中使用 ViewBag 及其他

自定义一个 TagHelper       ViewContext 引用的空间 using Microsoft.AspNetCore.Mvc.Rendering;

   [HtmlTargetElement("card")]
    public class CardTagHelper: TagHelper
    {
        public string Title { get; set; }
        public string Icon { get; set; }
        public string Url { get; set; }
        public string Tag { get; set; }

        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext viewContext { get; set; }

        IWorkOrderService workOrderService;
        public   CardTagHelper(IWorkOrderService workOrderService)
        {
            this.workOrderService = workOrderService;
        }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = Tag??"div";
            output.TagMode = TagMode.StartTagAndEndTag;

            
            var preContent = new StringBuilder();
            preContent.Append("<a>test</a>");
            viewContext.ViewBag.zhangsan = Title;
            int count = 0;
            var list = workOrderService.PageFind(0, null, null, null, null, null, 0, 1, 10, out count);
            viewContext.ViewBag.list = list;
            viewContext.ViewBag.count = count;

            output.PreContent.SetHtmlContent(preContent.ToString());
            output.PreContent.SetContent(Icon);
        }
    }

 Microsoft.AspNetCore.Mvc 中也有一个 ViewContext ,注意不要引用错

 

前端的写法
引入名称和所在程序集
@addTagHelper  CooperAdmin.CardTagHelper,CooperAdmin

这里嵌套调用
<card title="myTitle" icon="myIcon" url="redirectUrl">
    @ViewBag.zhangsan
    <ul>
        @foreach (var li in ViewBag.list)
        {
            <li>@li.Id, @li.Name</li>
        }
    </ul>


    <card title="myTitle2" icon="myIcon2" url="redirectUrl2">
    </card>
</card>

 

 

生成的代码:

<div>myIcon
    myTitle
    <ul>
            <li>6643, 苍茫的天涯是我的爱</li>
            <li>6642, 苍茫的天涯是我的爱</li>
            <li>6641, 苍茫的天涯是我的爱</li>
            <li>6640, 苍茫的天涯是我的爱</li>
            <li>6639, 苍茫的天涯是我的爱</li>
            <li>6638, 苍茫的天涯是我的爱</li>
            <li>6637, 苍茫的天涯是我的爱</li>
            <li>6636, 动可爱的人</li>
            <li>6635, 动的收</li>
            <li>6634, 动的收</li>
    </ul>


    <div>myIcon2
    </div>
</div>

 

posted @ 2021-07-19 15:28  Myisqq  阅读(138)  评论(0编辑  收藏  举报