Subby
Subby

Reputation: 5480

ASP.NET MVC - Simple If Else

For some reason I can't seem to get my head around why I get a The if block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup. error in my ASP.NET MVC Application.

@foreach (var image in Model.Images)
{
    if (counter == Model.Images.Count - 1)
    {
        <div style="float: left; height: 250px; padding-right: 5px;">
    }
    else
    {
        <div style="float: left; height: 200px; padding-right: 5px;">
    }
    ....
    ....

Prior to the above, I was simply doing: <div style="float: left; height: 200px; padding-right: 5px;">, however I am in need of this If Else to make it look better.

What am I doing wrong in the If Else statement?

Upvotes: 1

Views: 920

Answers (5)

Cosmin
Cosmin

Reputation: 2214

Check if @ from foreach is needed and also try to append @: in front of every div

Upvotes: 0

Adrian Wragg
Adrian Wragg

Reputation: 7411

Your problem is that the MVC parser is interpreting your code as you having left an open <div> sitting around. Rather than opening two, try reworking your code and outputting just one:

@foreach (var image in Model.Images)
{

    int height;

    if (counter == Model.Images.Count - 1)
    {
        height = 250;
    }
    else
    {
        height = 200;
    }

    <div style="float: left; height: @(height.ToString()+"px"); padding-right: 5px;">
        ...
        ...
    </div>
}

It could also be done in an even more compact manner:

@foreach (var image in Model.Images)
{

    bool condition = (counter == Model.Images.Count - 1)

    <div style="float: left; height: @( condition ? "200px" : "250px"); padding-right: 5px;">
        ...
        ...
    </div>
}

Upvotes: 2

gregjer
gregjer

Reputation: 2843

I would try to replace if/else completely like that:

 <div style="@(counter == Model.Images.Count - 1 ? "float: left; height: 250px; padding-right: 5px;" : "float: left; height: 200px; padding-right: 5px;")">

Upvotes: 1

Nick
Nick

Reputation: 2335

Try wrapping the whole thing in @{ ... }. And remove the @ symbols from the existing syntax.

Upvotes: 0

Erik Schierboom
Erik Schierboom

Reputation: 16656

This should work:

@foreach (var image in Model.Images)
{
    if (counter == Model.Images.Count - 1)
    {
        <text><div style="float: left; height: 250px; padding-right: 5px;"></text>
    }
    else
    {
        <text><div style="float: left; height: 200px; padding-right: 5px;"></text>
    }
}

Upvotes: 1

Related Questions