RenderSection已定义但未呈现

时间:2011-07-12 19:08:27

标签: asp.net asp.net-mvc

我正试图让我的网站的导航栏有点动态。 如果categoryId等于0,我会删除一些按钮,否则我会全部显示:

_Layout.cshtml:

<body>
    <div class="page">
        <div id="header">
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>     
            <div id="menucontainer">
                @if (IsSectionDefined("Navigation"))
                {
                    {RenderSection("Navigation", false);}
                }
                else
                {
                    <p>No navigation setup!</p>
                }
            </div>
        </div>
        <div id="main">
            <div id="contentwrapper">
                @RenderBody()
            </div>
            <div id="footer">
            </div>
        </div>
    </div>
</body> 
来自我的HomeController的

Index.cshtml:

@model Project2.ViewModels.ProjectCategoryListViewModel

@{
    ViewBag.Title = "Home Page";
}

@section Navigation {
    @{Html.RenderAction("LayoutNav", "Home", new { CategoryId = 0 });}
}

<!-- Rest of the page's code -->
来自我的CategoryController的

Index.cshtml:

@model Project2.ViewModels.Categories.CategoryIndexViewModel

@{
    ViewBag.Title = "Category Index";
}

@section Navigation {
    @{Html.RenderAction("LayoutNav", "Home", new { CategoryId = Model.Category.Id });} 
}

<!-- Rest of the page's code -->

我尝试了完全相同的设置,但没有RenderAction,只是直接输入html但我不断收到此错误消息:

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Navigation". 

类别和家庭控制器中的索引操作是返回视图的直接ActionResults。

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

RenderSection语法错误。试一试:

@if (IsSectionDefined("Navigation"))
{
    @RenderSection("Navigation", false)
}
else
{
    <p>No navigation setup!</p>
}

答案 1 :(得分:2)

我写了一篇博文,其中包含一个帮助方法,用于在RenderSection调用中指定默认内容:http://haacked.com/archive/2011/03/05/defining-default-content-for-a-razor-layout-section.aspx

它可以让您执行以下操作:

@RenderSection("Navigation", @<p>No navigation setup!</p>)