Mod Operators in Razor
This website is no longer actively supported
Written by pullella 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
page revision: 3, last edited: 15 Mar 2013 20:27
Thanks this was exactly what I was looking for!
Had the same problem and I though Visual Studio was just erroring out. It made sense logically and I had a colleague who's built quite a few public consumer sites in razor check it out and he couldn't figure it out. Cheers!