Search code examples
asp.net-corerazorrazor-pagesasp.net-core-6.0

The tag helper 'form' must not have C# in the element's attribute declaration area


On a Razor Page I have:

<form @{ if (Model.Topic is not null) { <text>x-init="[email protected]"</text> } } method="post">

I want to render x-init="[email protected]" only if Model.Topic has a value.

I am getting the following error:

The tag helper 'form' must not have C# in the element's attribute declaration area.

I tried a few options but I always end up with a compilation error like a quotes problem.

How to solve this?


Solution

  • Note that Razor has special-case handling for HTML element attributes that are rendered using the Razor syntax <elementName attribute-name="@( value )"> (or just <elementName attribute-name="@value">): when value is null then Razor will omit the attribute name and value entirely.

    So this should work:

    @{
        String? xInitAttribValue = null;
        if( !String.IsNullOrWhiteSpace( this.Model?.Topic ) )
        {
            xInitAttribValue = "data.topic=" + this.Model.Topic;
        }
    }
    
    <!-- etc -->
    
    <form x-init="@xInitAttribValue">
    
    </form>
    

    • When this.Model.Topic is null/empty/whitespace then Razor will render just <form>.
    • When this.Model.Topic is not null/empty/whitespace (e.g. "123abc") then Razor will render something like <form x-init="data.topic=123abc">.

    It can be inlined too:

    <form x-init="@( this.Model.Topic is not null ? ( "data.topic=" + this.Model.Topic ) : null )">
    

    or use an interpolated string: (I'm not a fan of interpolated strings because they default to CurrentCulture and make it hard to use InvariantCulture, *grumble*)

    <form x-init="@( this.Model.Topic is not null ? ( $"data.topic={this.Model.Topic}" : null)">