忽略razor _layout.cshtml中的renderbody

时间:2013-09-02 22:50:32

标签: c# asp.net-mvc asp.net-mvc-4 razor

我有一个页面,您需要登录才能观看。所以我想试试这段代码:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta charset="utf-8" />
    <title>@ViewBag.Title - Meine ASP.NET MVC-Anwendung</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")
    @if (!Request.IsAuthenticated) {
        @Styles.Render("~/Content/signin")
    }
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @if (Request.IsAuthenticated) {
        <header class="navbar navbar-fixed-top" role="banner">
            <div class="container">
                <div class="navbar-header">
                    <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="../">Home</a>
                </div>
                <nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation">
                    <ul class="nav navbar-nav">
                        <li class="active">
                            <a href="#">Link 1</a>
                        </li>
                        <li>
                            <a href="#">Link 2</a>
                        </li>
                        <li>
                            <a href="#">Link 3</a>
                        </li>
                        <li>
                            <a href="#">Link 4</a>
                        </li>
                        <li>
                            <a href="#">Link 5</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </header>
        <div id="body">
            @RenderBody()
        </div>
    } else {
        @RenderBody()
    }
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
    <footer>
        <p>&copy; @DateTime.Now.Year - Meine ASP.NET MVC-Anwendung</p>
    </footer>
</body>
</html>

但是当我开始这个时,我得到了这个例外

The RenderBody-Method wasn't called for the layoutpage "~/Views/Shared/_Layout.cshtml"

如何让剃须刀忽略RenderBody方法?

1 个答案:

答案 0 :(得分:11)

请注意,您实际上可以&#34;忽略&#34;如果你真的想要的内容。通常,您在视图代码中编写@RenderBody(),它会评估正文内容,将其添加到HelperResult中,然后将其写入输出流。这样做,MVC将身体标记为已渲染。你可以通过编写@{ RenderBody(); }(注意大括号)或只是RenderBody();(如果已经在代码上下文中)来欺骗它认为身体已被渲染而不实际写任何东西。这会评估正文内容,而不会将其实际写入输出流。