Skip to main content
 首页 » 编程设计

c#之如何在 MVC3 的 View 文件中使用多 FOR 循环

2024年02月20日14xing901022

我在尝试使用多个 FOR 循环(for in for)时遇到问题。错误信息是:

Parser Error Message: The for 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.

这是我的代码,问题来自第一个 :( 。

<table width="100%" border="1"> 
@for (int q = 0; q < quanList.Count; q++) {      
    <tr> 
        <td>@quanList[q]</td> 
 
        @for (int s = 0; s < sizeList.Count; s++) {          
            <td><input type="text" name="txtval" style="width:80px" /></td> 
        } 
    </tr> 
}    
</table> 

非常感谢您的任何建议和想法。

我想显示一个包含动态行和列的表格,两个列表已从 Controller 创建并通过 ViewBag 解析以查看:

@{ 
List<string> sizeList = (List<string>)ViewBag.SizeList; 
List<string> quanList = (List<string>)ViewBag.QuanList; 

请您参考如下方法:

<table width="100%" border="1"> 
@{List<int> quanList = new List<int>(); 
  List<int> sizeList = new List<int>(); 
} 
for (int q = 0; q < quanList.Count(); q++) { 
<tr> 
    <td>@quanList[q] 
    </td> 
    for (int s = 0; s < sizeList.Count(); s++){ 
    <td> 
        <input type="text" name="txtval_@q_@s" style="width: 80px" /> 
    </td> 
    } 
</tr> 
} } 
</table> 

试试这个:

尝试将此 @q @s 重命名为其他名称。如果您将它们混在一起,MVC 会将其视为普通的 @,例如 example@example.com。

{int textFieldName = "txtval_" + q + 
        "_" + s; 
        <td> 
            <input type="text" name="@textFieldName" style="width: 80px" /> 
        </td> 
        }