Mod Operators in Razor

This website is no longer actively supported

Written by pullellapullella on 17 Jun 2011 12:13

Overview

I recently was playing with the Netflix OData API and wanted to create a list of movie covers in columns of 5. I created a table and began looping through my movies using the mod operator in C# (%). That was when I ran into problems.

The problem

Creating the table was straightforward, I just needed to start a TR tag, and in a loop, end the TR tag and begin a new TR tag. However, if you attempt to do something like the following, you will get an error about the starting tag not having an ending tag

        <tbody>
            <tr>
            @{
                int i = 0;
                foreach (MyMovies.NetflixOData.Title title in Model.Movies) {
                    if ((i % 5) == 0) {
                        </tr><tr>
                    }

                    <td align="center"><img src="@title.BoxArt.SmallUrl" /></td>
                    i++;
                }
            }
            </tr>
        </tbody>

The trick is to tell the razor page that the ending TR tag should be followed by a starting TR tag. The magic is in the Razor command @:

The following code solved my problem

        <tbody>
            <tr>
            @{
                int i = 0;
                foreach (MyMovies.NetflixOData.Title title in Model.Movies) {
                    if ((i % 5) == 0) {
                        @:</tr><tr>
                    }

                    <td align="center"><img src="@title.BoxArt.SmallUrl" /></td>
                    i++;
                }
            }

            </tr>
        </tbody>

Discussion Closed

Add a New Comment

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License