【问题标题】:for loop inside if block in HTMLHTML中的if块内的for循环
【发布时间】:2014-11-21 23:07:04
【问题描述】:

我很难理解为什么这不起作用:

@if ((Model.doaFormGroupDocuments.Count != 0) || (Model.doaFormGroupDocuments != null))
{
    @for(var i = 0; i < Model.doaFormGroupDocuments.Count; i++)
    {
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Checked)
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Id)
        @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Name)
    }
}

我在 for 循环旁边的 @ 下看到一条红色错误行。这在 HTML 中是不允许的吗?

【问题讨论】:

  • 旁注:你可能会遇到一个错误,如果doaFormGroupDocuments == null.Count 将不可用,因此 if 语句中的比较顺序应与此相反(并且它应该是&amp;&amp; 而不是||): if ((Model.doaFormGroupDocuments != null) &amp;&amp; (Model.doaFormGroupDocuments.Count != 0))

标签: c# html asp.net-mvc razor


【解决方案1】:

John,这看起来像 ASP.NET MVC,我假设是这样的。

如果你有两个上下文,HTML 和 Razor,任何时候你有一个 @ 它切换到 Razor 上下文,当你有一个 HTML 标签时,&lt;text&gt;@: 它切换 HTML 上下文。

Visual Studio 抱怨是因为您处于剃刀上下文中(来自您的 if 语句),并尝试使用 @for 再次进入剃刀上下文,您只需要在 for 循环之前删除 @。另请注意,for 循环中的三个帮助器调用将得到正确处理,因为它知道您正在那里返回 IHtmlStrings。

【讨论】:

    【解决方案2】:

    您已经在剃须刀的代码块中,因此您不需要在 for 关键字之前添加 @

    @if ((Model.doaFormGroupDocuments.Count != 0) || (Model.doaFormGroupDocuments != null))
    {
        for(var i = 0; i < Model.doaFormGroupDocuments.Count; i++)
        {
            @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Checked)
            @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Id)
            @Html.HiddenFor(model => model.doaFormGroupDocuments[i].Name)
        }
    }
    

    看到这个问题

    Unexpected "foreach" keyword after "@" character

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多