如何只用剃刀返回HTML正文的内容?

时间:2019-04-05 16:10:34

标签: c# razor .net-core

我有一个页面,我只想有条件地返回body标记的内容。条件是ViewBag.BodyOnly

我尝试了以下操作,但收到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错误:

@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>

}

我在这里想念什么?

2 个答案:

答案 0 :(得分:1)

您最好的选择是为body标签内的内容提​​取部分内容,例如:

@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")
}

然后在_body.cshtml中输入

<div>this</div>
<div>that</div>

答案 1 :(得分:1)

问题是,当您需要以节点的形式考虑HTML时,您就以标签的形式考虑HTML。

当您执行以下操作时:

@if (something) {
     <html>
}

您的if语句从节点的前半部分中断,其余部分则被冷落。

为了完成您要完成的任务,请分解身体部分,然后在两个地方使用它:

@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>
}