Friday, September 27, 2013

ASP.NET MVC - using tr tag in if statement within a loop (Razor)

When rows to display are unknown, one can use for loop and display one row per line. For example, if 4 rows are to be displayed, they can be shown as follows.
Item1
Item2
Item3
Item4

But what if we want to display multiple items in one line? What if we want to display 2 columns in a row like this?
Item1 Item2
Item3 Item4

The following example shows how to display multiple items in a line. First, (model) data has unknown number of rows and we use foreach loop to display all data (Names in this example). COLUMN_SIZE is chosen to be 3, which means 3 columns in a row.
@{
    List<string> Names = new List<string>();
    Names.Add("Item1");
    Names.Add("Item2");
    Names.Add("Item3");
    Names.Add("Item4");
    Names.Add("Item5");

    int count = 0;
    int COLUMN_SIZE = 3;
}

<div>
    <table>  
        <tr>
        @foreach (var name in Names)
        {                                         
            <th>
                @Html.Label(name)
            </th>
            <td>                
                @Html.TextBox(name)
            </td>
                
            if (++count % COLUMN_SIZE == 0) 
            {                     
                @:</tr> 
                @:<tr> 
            }
        }
    </table>    
</div>

foreach loop gets data one by one and put it into td tag. Please note that we put tr tag before foreach to initiate tr open tag. For tr close tag, keep counting the counter and once it reaches column size boundary, we put tr close tag and then initiate another tr open tag. Razor engine keeps tracking of open/close tag match and implicitly adds tr open / close tag during its rendering.
In Razor, @: represents the next text is considered as a plain text.

No comments:

Post a Comment