标签助手不知道除了您为其属性提供的输入之外的任何内容。所以你想创建一个标签助手,你可以使用如下:
@model WebApplication4.Models.Sale
...
<customer asp-for="CustomerId" />
然后您将声明与asp-for 属性关联的ModelSource 类型的属性。这将使您不仅可以访问属性的值,还可以访问如下元数据(以及更多!):
- 属性值:
source.Model
- 属性名称:
source.Name
- 容器型号类型:
source.Metadata.ContainerType
-
IsRequired 标志:
source.Metadata.IsRequired
您还将在 VS 中获得智能感知,以便为 asp-for 模型选择模型中的属性之一,如果该值不是模型属性的名称,则会引发错误。
作为一个例子,看看这个标签助手:
public class CustomerTagHelper: TagHelper
{
[HtmlAttributeName("asp-for")]
public ModelExpression Source { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "p";
output.TagMode = TagMode.StartTagAndEndTag;
var contents = $@"
Model name: {Source.Metadata.ContainerType.FullName}<br/>
Property name: {Source.Name}<br/>
Current Value: {Source.Model}<br/>
Is Required: {Source.Metadata.IsRequired}";
output.Content.SetHtmlContent(new HtmlString(contents));
}
}
那么如果你有这两个模型:
public class Sale
{
[Required]
public string CustomerId { get; set; }
}
public class Promotion
{
public string CustomerId { get; set; }
}
这两个动作和视图中使用了哪些:
public IActionResult Sale()
{
return View();
}
@model WebApplication4.Models.Sale
...
<customer asp-for="CustomerId" />
public IActionResult Promotion()
{
return View(new Models.Promotion { CustomerId = "abc-123" });
}
@model WebApplication4.Models.Promotion
...
<customer asp-for="CustomerId" />
将产生这些输出:
Tag helper for: WebApplication4.Models.Sale
Property name: CustomerId
Current Value:
Is Required: True
Model name: WebApplication4.Models.Promotion
Property name: CustomerId
Current Value: abc-123
Is Required: False