标签助手不知道比你提供什么样的作为其属性输入的任何其他。所以,你要创建一个可以使用如下标签帮手:
@model WebApplication4.Models.Sale
...
<customer asp-for="CustomerId" />
然后,你将宣布与asp-for
属性相关联ModelSource
类型的属性。这将让你访问不只是财产的价值,而且元数据,如下面的(和更多!):
- 属性值:
source.Model
- 属性名称:
source.Name
- 容器模型类型:
source.Metadata.ContainerType
- IsRequired标志:
source.Metadata.IsRequired
您也将获得intellisen在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 = [email protected]"
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));
}
}
然后,如果你有这2种型号:
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
而不是“Source.Metadata.IsRequired”我使用“For.Metadata.IsRequired”。作品。 – Beetlejuice
是的,无论你使用什么名称fpr类型'ModelExpression'属性 –
如何访问其他属性? – HamedH