Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Razor not like this?

Ive got a mega annoying problem I have a view with:

@{

        if(ViewBag.Section == "Home")
        {
           <div id="headerfrontPage">   
        }
        else
        {
            <div id="header">   
        }


     }

And I get a compilation error:

The code 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.

How do I conditionally write a div? Its for a hack bascially...

like image 316
Exitos Avatar asked Nov 07 '11 17:11

Exitos


4 Answers

You can use the same construct when you wrap your div's inside element like:

@if (ViewBag.Section == "Home")
{
    <text><div id="headerfrontPage"></text>
}
else
{
    <text><div id="header"></text>
}

Or you use razor syntax @: like

@if (ViewBag.Section == "Home")
{
    @:<div id="headerfrontPage">
}
else
{
    @:<div id="header">
}

But for your current situation I would prefer Ron Sijm's solution:

@{
var divName = ViewBag.Section == "Home" ? "headerfrontPage" : "header";
}

<div id="@divName"> 
like image 160
Siim Avatar answered Oct 13 '22 01:10

Siim


I suspect it is because your divs are not closed, so razor assumes that the closing brace is actually part of the div content.

You might try outputting the entire div content within your code there, including the closing tag, or output the div tag with a Response.Write, or something similar, so there is no confusing markup.

EDIT: also, maybe enclosing your div tag in a

<text></text>

might be worth a try.

like image 26
Andrew Barber Avatar answered Oct 13 '22 00:10

Andrew Barber


You could try this:

@{
string divName;

    if(ViewBag.Section == "Home")
    {
       divName = "headerfrontPage";
    }
    else
    {
        divName = "header";
    }
}

<div id="@divName"> 

I'm not sure if that will help, it a long shot. But at least imo that looks better...

like image 7
Ron Sijm Avatar answered Oct 13 '22 00:10

Ron Sijm


Try this:

@if (ViewBag.Section == "Home")
{
    <text> <div id="headerfrontPage"> </text>
}
else
{
    <text> <div id="header"> </text>
}
like image 2
gdoron is supporting Monica Avatar answered Oct 13 '22 01:10

gdoron is supporting Monica