MVC6 (ASP.NET5) 自定义TagHelper

1) 在 _ViewImports.cshtml 中引入TagHelper类所在的 Assembly . (注意不是namespace)  :

@addTagHelper "*, WebApplication1"

 2) 创建TagHelper类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNet.Razor.Runtime.TagHelpers;
 6 using Microsoft.AspNet.Razor.TagHelpers;
 7 
 8 namespace WebApplication1.TagHelpers
 9 {
10     // You may need to install the Microsoft.AspNet.Razor.Runtime package into your project
11     [HtmlTargetElement("field")]
12     public class FieldTagHelper : TagHelper
13     {
14         [HtmlAttributeName("label")]
15         public string Label { get; set; }
16 
17         [HtmlAttributeName("cols")]
18         public int ColumnCount { get; set; }
19          
20         public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
21         {
22             output.TagName = "div";
23             output.Attributes.Add("class", "form-group");
24 
25             var childContent = await output.GetChildContentAsync();
26 
27             output.Content.SetHtmlContent($@" 
28 <label class='col-md-{ColumnCount} control-label'>{Label}</label>
29 <div class='form-value col-md-{12 - ColumnCount}'>{childContent.GetContent()}</div>"); 
30         }
31     }
32 }

3)使用自定义Tag:

1 <field label="Test Label" cols="4">
2     <input asp-for="TestName" class="form-control" />
3 </field>

 

转载于:https://www.cnblogs.com/ybst/p/5028277.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值