kfuglsang
kfuglsang

Reputation: 2505

MVC3 Razor Syntax troubles

I'm trying to make a very simple view using Razor syntax in MVC3, but it seems I can't get the syntax right.

I have a simple table like this

<table>
                <tr>
                    @{
                        var counter = 0;
                    }

                    @foreach (var category in ViewBag.Categories)
                    {
                        counter++;
                        <td>
                            <input type="checkbox" checked="checked" name="@("category" + category.Code)" />
                            @category.Description
                        </td>

                        if (counter % 2 == 0)
                        {
                            </tr>
                            <tr>
                        }
                    }
                </tr>
            </table>

When I insert the and inside the if-statement, I receive this error

The using block is missing a closing "}" character.

If I try to wrap those two tags inside and , I get this error instead:

The "tr" element was not closed.

Upvotes: 8

Views: 5795

Answers (3)

Martin Buberl
Martin Buberl

Reputation: 47114

I would say you're missing the @ in front of the if statement. Try @if(counter % 2 == 0).

Hope that helps.

Update

I checked it out and the answer from GvS seems to work just fine. The @ is not necessary for the if statement.

@for (int i = 0; i < 5; i++)
{
    if (i == 3)
    {
        @:</tr><tr>
    }
}

Upvotes: 3

GvS
GvS

Reputation: 52518

Your </tr><tr> messes up the "flow" of the html/code mix.

You are closing the tr-tag on a different level, not a different level in the html, but inside the code. You should trick razor into outputting html, that it does not parse itself.

You could include them like this:

@:</tr><tr>

or

@Html.Raw("</tr><tr>")

The result:

                        if (counter % 2 == 0)
                        {
                            @:</tr><tr>
                        }

Click for Haack's quick reference of Razor syntax

Upvotes: 14

jgauffin
jgauffin

Reputation: 101130

You are mixing HTML and code in the foreach. That's why you get problems.

Either use <text></text> block around the HTML, or do the following:

<table>
    <tr>
        @{
            var counter = 0;
        }

        @foreach (var category in ViewBag.Categories)
        {
            @{ 
                counter++; 
            }

            <td>
                <input type="checkbox" checked="checked" name="@("category" + category.Code)" />
                @category.Description
            </td>

            @if (counter % 2 == 0)
            {
                </tr>
                <tr>
            }
        }
    </tr>
</table>

Upvotes: 0

Related Questions