Asp.Net 核心 Razor Taghelpers - 强制参数
Asp.Net core Razor Taghelpers - mandatory parameters
如果我像这样创建 EmailTagHelper:
public class EmailTagHelper : TagHelper
{
public string EmailAddress { get; set; }
public string Content { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a";
output.Attributes.SetAttribute("href", "mailto:" + this.EmailAddress);
output.Content.SetContent(this.Content);
}
}
我可以这样使用它:
<email content="Mail me!" email-address="hello@world.com"></email>
但是,我也可以在 Visual Studio 或编译错误的情况下执行此操作:
<email content="Mail me - but where!?"></email>
有没有办法将属性标记为强制属性,以便它们可以触发编译错误或至少在 Visual Studio 中出现红色波浪线,这样错误就不会在运行时发生?
将所需的属性名称添加到 HtmlTargetElement
:
[HtmlTargetElement("email", Attributes ="email-address")]
public class EmailTagHelper : TagHelper
{
public string EmailAddress { get; set; }
public string Content { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
// ...
}
}
此解决方案不会触发编译器错误或显示警告消息,但至少 html 标记不会在编辑器中以 粗体绿色 呈现,直到您提供所需的属性。
如果想在未提供属性时抛出异常,必须从HtmlTargetElement
属性中移除:
[HtmlTargetElement("email")]
public class EmailTagHelper : TagHelper
{
public string EmailAddress { get; set; }
public string Content { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (string.IsNullOrWhiteSpace(EmailAddress))
throw new ArgumentNullException(nameof(EmailAddress));
// ...
}
}
如果我像这样创建 EmailTagHelper:
public class EmailTagHelper : TagHelper
{
public string EmailAddress { get; set; }
public string Content { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a";
output.Attributes.SetAttribute("href", "mailto:" + this.EmailAddress);
output.Content.SetContent(this.Content);
}
}
我可以这样使用它:
<email content="Mail me!" email-address="hello@world.com"></email>
但是,我也可以在 Visual Studio 或编译错误的情况下执行此操作:
<email content="Mail me - but where!?"></email>
有没有办法将属性标记为强制属性,以便它们可以触发编译错误或至少在 Visual Studio 中出现红色波浪线,这样错误就不会在运行时发生?
将所需的属性名称添加到 HtmlTargetElement
:
[HtmlTargetElement("email", Attributes ="email-address")]
public class EmailTagHelper : TagHelper
{
public string EmailAddress { get; set; }
public string Content { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
// ...
}
}
此解决方案不会触发编译器错误或显示警告消息,但至少 html 标记不会在编辑器中以 粗体绿色 呈现,直到您提供所需的属性。
如果想在未提供属性时抛出异常,必须从HtmlTargetElement
属性中移除:
[HtmlTargetElement("email")]
public class EmailTagHelper : TagHelper
{
public string EmailAddress { get; set; }
public string Content { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (string.IsNullOrWhiteSpace(EmailAddress))
throw new ArgumentNullException(nameof(EmailAddress));
// ...
}
}