I have the following code and it is the nightmare that I feared when I saw the razor syntax in the project that got dumped in my lap. It doesn’t understand what part is code and what part HTML.
@for (int i = 0; i < Model.Instructor.Classes.Count;i++ )
{
var c = Model.Instructor.Classes[i];
var mod = (i%2);
if (mod==1)
{
<tr>
}
<td>
@c.Subject @c.CatalogNumber - @c.Section
</td>
if (mod==0)
{
</tr>
}
}
I am just trying to do a simple multicolumn table because the list of items is too long on the page.It prints out my if logic as if it were text. If I put a @ in front of it, it gives me a syntax error. It seems there should be a control for this but all the controls I have seen are worried about alt-styles and not the number of columns to put the data.
For starters, remove the semi-colons. Razor syntax doesn’t use them. More to the point, you shouldn’t be writing things like
var c = Model.Instructor.Classes[i];in your view. The view should just bind to the view model, which should be built/returned form the controller.You can, within your controller, set
ViewBagproperties which map to these values that you want. Be actual logic like this shouldn’t be in the view.Finally, if Razor is having trouble parsing which of your terms it needs to parse (which, as you allude to at the beginning of your question, is a potential pitfall), you can use the
<text>tag to explicitly outline which parts should be text.