ASP中Razor语法的嵌套代码.NET MVC

本文关键字:代码 NET MVC 嵌套 Razor 语法 ASP | 更新日期: 2023-09-27 17:59:38

我正在开发一个ASP。NET MVC 4应用程序使用RAZOR。该应用程序基本上是一个带有组的记录列表。为了生成一个组标题和每个组的记录,我使用了以下内容:

@{ string currentGroupName = string.Empty; }
@foreach (DataRow row in ViewBag.TableRows) {
  string groupName = Convert.ToString(row["Group"]); 
  if (groupName != currentGroupName) {
    <div style="width:98%;" class="nfo">@groupName</div>
    <table id="groupTable" border="0" class="t" style="margin-left:6px;">
      <thead>
        <tr>
          <th>Header 1</th>
          <th>Header 2</th>
          <th>Header 3</th>
        </tr>
      </thead>
      <tbody>
    }
                  ...
  @if (groupName != currentGroupName) {
      </tbody>
    </table>
    currentGroupName = groupName;
  }
}

当我执行这个代码时,我得到一个错误,上面写着:

Parser Error
The foreach block is missing a closing "}" character.  Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

我做错了什么?

ASP中Razor语法的嵌套代码.NET MVC

您可以尝试使用@:运算符:

@{ string currentGroupName = string.Empty; }
@foreach (DataRow row in ViewBag.TableRows) 
{
    string groupName = Convert.ToString(row["Group"]); 
    if (groupName != currentGroupName) 
    {
        <div style="width:98%;" class="nfo">@groupName</div>
        @:<table id="groupTable" border="0" class="t" style="margin-left:6px;">
            <thead>
                <tr>
                    <th>Header 1</th>
                    <th>Header 2</th>
                    <th>Header 3</th>
                </tr>
            </thead>
            @:<tbody>
    }
    ...
    @if (groupName != currentGroupName) 
    {
            @:</tbody>
        @:</table>
        @{currentGroupName = groupName;}
    }
}