MVC剃刀Foreach循环(两次)不起作用,包围错误
问题描述:
考虑:MVC剃刀Foreach循环(两次)不起作用,包围错误
//A Strongly typed view model where the data is passed in perfectly.
<table id="dt1">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.Name)
</th>
<th>@Html.DisplayNameFor(model => model.Area)
</th>
<th>@Html.DisplayNameFor(model => model.Hours)
</th>
<th>@Html.DisplayNameFor(model => model.Minutes)
</th>
<th>@Html.DisplayNameFor(model => model.PercentOfTotal)
</th>
</tr>
</thead>
@foreach (var current in names)
{
<tr>
<td>@current</td>
</tr>
//Notice this is the problem area.
//I have a foreach inside of another one. Razor seems to think I need another "}"
//But the compiler tells me I need it at line 1 above
var stuff = @Model.Where(p => p.Name == current);
foreach (var item in stuff)
{
<tr>
<td>@item.Area</td>
<td>@item.Hours</td>
<td>@item.Minutes</td>
<td>@item.PercentOfTotal</td>
</tr>
}
}
</table>
不管我怎么努力剃刀不喜欢foreach循环!除非我做错了什么......如果我忽略设计器错误并运行它,运行时会告诉我我需要另一个“}”,除非我真的很累,我可以看到我错过了一个括号。当我删除第二个foreach时没有编译器错误,但只要我添加第二个...问题。
答
取出@
在@Model...
....
var stuff = Model.Where(p => p.Name == current);
foreach (var item in stuff)
{
....
@-Named C# Variables + Nested Blocks Generate Broken Code了解更多信息
答
你也可以这样写
var stuff = Model.Where(p => p.Name == current);
@foreach (var item in stuff)
{
<tr>
<td>@item.Area</td>
<td>@item.Hours</td>
<td>@item.Minutes</td>
<td>@item.PercentOfTotal</td>
</tr>
}
相信会比使用
Model.AsNoTracking().Where(p => p.Name == current).ToList()
和
@for (int i = 0; i < stuff.Count; i++)
更好的数据库和EF提供。 因为如果你不想改变数据,连接越少越好。
p.s.对不起我的英语,我正在学习它)