Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 346
kfuglsang Avatar asked Jan 28 '11 10:01

kfuglsang


2 Answers

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

like image 171
GvS Avatar answered Oct 19 '22 06:10

GvS


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>
    }
}
like image 3
Martin Buberl Avatar answered Oct 19 '22 06:10

Martin Buberl