Reputation: 61636
I have the a page and I want to conditionally return the contents of the body
tag only. The condition is ViewBag.BodyOnly
I've tried the following, but I get 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:
@if (ViewBag.BodyOnly) {
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Title</title>
</head>
<body>
}
<div>this</div>
<div>that</div>
@if (ViewBag.BodyOnly) {
</body>
</html>
}
What am I missing here?
Upvotes: 0
Views: 227
Reputation: 101730
The problem is that you're thinking of HTML in terms of tags when you need to think of it in terms of nodes.
When you do something like this:
@if (something) {
<html>
}
Your if-statement is lopping off the first half of a node, and the rest of it is left out in the cold.
In order to do what you're trying to accomplish, factor out the body portion, and then use that in two places:
@helper Body()
{
<div>this</div>
<div>that</div>
}
@if (ViewBag.BodyOnly)
{
@Body()
}
else
{
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Title</title>
</head>
<body>
@Body()
</body>
</html>
}
Upvotes: 1
Reputation: 113
Your best bet is to extract a partial for the content inside your body tag for example:
@if (ViewBag.BodyOnly)
{
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Title</title>
</head>
<body>
@Html.Partial("_body")
</body>
</html>
}
else
{
@Html.Partial("_body")
}
Then in _body.cshtml
:
<div>this</div>
<div>that</div>
Upvotes: 1