【问题标题】: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 语法 &lt;elementName attribute-name="@( value )"&gt;(或只是 &lt;elementName attribute-name="@value"&gt;)呈现的 HTML 元素属性进行了特殊处理:当 valuenull 时,Razor 将完全省略属性名称和值。

    所以这应该工作:

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

    • this.Model.Topicnull/empty/whitespace 时,Razor 将只渲染&lt;form&gt;
    • this.Model.Topic不是null/empty/whitespace(例如“123abc”)然后 Razor 将呈现类似 &lt;form x-init="data.topic=123abc"&gt; 的内容。

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 2020-02-08
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      相关资源
      最近更新 更多