【问题标题】:The tag helper 'form' must not have C# in the element's attribute declaration area标签助手\'form\'在元素的属性声明区域中不能有C#
【发布时间】:2022-10-01 02:34:11
【问题描述】:
在剃刀页面上,我有:
<form @{ if (Model.Topic is not null) { <text>x-init=\"data.topic=@Model.Topic\"</text> } } method=\"post\">
我只想在Model.Topic 有值的情况下渲染x-init=\"data.topic=@Model.Topic\"。
我收到以下错误:
The tag helper \'form\' must not have C# in the element\'s attribute declaration area.
我尝试了一些选项,但我总是以编译错误结束,比如引号问题。
如何解决这个问题?
标签:
asp.net-core
razor
razor-pages
asp.net-core-6.0
【解决方案1】:
请注意,Razor 对使用 Razor 语法 <elementName attribute-name="@( value )">(或只是 <elementName attribute-name="@value">)呈现的 HTML 元素属性进行了特殊处理:当 value 为 null 时,Razor 将完全省略属性名称和值。
所以这应该工作:
@{
String? xInitAttribValue = null;
if( !String.IsNullOrWhiteSpace( this.Model?.Topic ) )
{
xInitAttribValue = "data.topic=" + this.Model.Topic;
}
}
<!-- etc -->
<form x-init="@xInitAttribValue">
</form>
- 当
this.Model.Topic 为null/empty/whitespace 时,Razor 将只渲染<form>。
- 当
this.Model.Topic 是不是null/empty/whitespace(例如“123abc”)然后 Razor 将呈现类似 <form x-init="data.topic=123abc"> 的内容。