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.

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>();

    int count = 0;
    int COLUMN_SIZE = 3;

        @foreach (var name in Names)
            if (++count % COLUMN_SIZE == 0) 

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.