JWP
JWP

Reputation: 6963

MVC Razor Foreach loop (twice) doesn't work, bracketing error

Given:

//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>

No matter what I try razor doesn't like to foreach loops! Unless I'm doing something wrong... If I ignore the designer errors and run it, the runtime tells me I need another "}", unless I'm really tired I just can see where I'm missing a bracket. There's no compiler errors when I remove the second foreach, but as soon as I add the 2nd one....problems.

Upvotes: 0

Views: 1491

Answers (2)

xsharnin
xsharnin

Reputation: 29

Also you can write like this

    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>
    }

I believe than use

    Model.AsNoTracking().Where(p => p.Name == current).ToList() 

and

    @for (int i = 0; i < stuff.Count; i++)

much better for Database and EF provide. Because if you don't want change data, the less connection the better.

p.s. sorry for my English, I am learning it )

Upvotes: 1

user3559349
user3559349

Reputation:

Remove the @ in @Model...

....
var stuff = Model.Where(p => p.Name == current);
foreach (var item in stuff)
{
  ....

@-Named C# Variables + Nested Blocks Generate Broken Code for additional information

Upvotes: 1

Related Questions