huynhtuanh
huynhtuanh

Reputation: 327

How to use multi FOR loop in a View file of MVC3?

I have a problem when trying to use multiple FOR loop (for in for). The error message is:

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.

Here is my code, the problem come from the first for :( .

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

Thank you very much for any suggestion and ideas.

I want to show a table with dynamic rows and columns, two list has been created from controller and parse to view via ViewBag:

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

}

Upvotes: 1

Views: 915

Answers (3)

Simon Whitehead
Simon Whitehead

Reputation: 65049

You need to escape your @ symbols by using double @:

<td><input type="text" name="txtval_@@q_@@s" style="width:80px" /></td>

Or if you require the q and s values, you can include brackets:

<td><input type="text" name="txtval_@(q)_@(s)" style="width:80px" /></td>

Upvotes: 1

Rajesh
Rajesh

Reputation: 1469

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

Try this :

Try renaming this @q @s to something else. If you mix them up , MVC will treat as a normal @ for example [email protected] .

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

Upvotes: 2

Ian Routledge
Ian Routledge

Reputation: 4042

Try changing the input name to the following:

<input type="text" name="txtval_@(q)_@(s)" style="width:80px" />

Those extra brackets should fix it

Upvotes: 1

Related Questions