Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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="data.topic=@Model.Topic"</text> } } method="post">

I want to render x-init="data.topic=@Model.Topic" only if Model.Topic has a value.

I am getting the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading