Search code examples
asp.net-mvcasp.net-corerazorasp.net-core-tag-helpers

Asp.Net core Razor Taghelpers - mandatory parameters


If I create an EmailTagHelper like this:

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);
    }
}

I can use it like this:

<email content="Mail me!" email-address="[email protected]"></email>

However, I can also do this without getting an error in Visual Studio or a compile error:

<email content="Mail me - but where!?"></email>

Is there a way to mark properties mandatory, so that they can trigger compile errors or at least a red squiggle in Visual Studio, so the error does not occur at runtime?


Solution

  • Add the required attribute name to the 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)
        {
            // ...
        }
    }
    

    This solution will not trigger compiler errors or show a warning message, but at least the html tag will not be rendered in bold green in the editor till you provide the required attributes.

    If you want to throw an exception when the attribute is not provided, it must be removed from the HtmlTargetElement attributes:

    [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));
    
            // ...
        }
    }