Search code examples
asp.netasp.net-mvcasp.net-mvc-4razorrazorengine

view sections cause problems if not rendered in layout


I'm converting an MVC aspx content place holder -> master page to an MVC razor section -> layout.

In the past when my aspx view came to something like this:

<asp:Content ID="HelpContent" ContentPlaceHolderID="HelpLink" runat="server">
    <a href="../../Support" target="HPhelp" title="Open GideonSoft Help">Help</a>
</asp:Content>

And the master page didn't have a corresponding HelpContent place holder (perhaps because a user was not authenticated) everything rendered fine (with no HelpContent section).

Now when I have a razor section defined that does not have a corresponding @RenderSection in the layout, I get this error:

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

Do I need to redesign this?

Is there a way I can have the view's HelpLink section render optionally if the layout gives it the green light?

EDIT:

I think there's some confusion, so let me re-summarize:

The layout logic looks like this:

if (User.IsLoggedIn) {
   @RenderSection( "HelpLinks", false);
}

But then the user isn't logged in, it doesn't render, and then .NET throws an exception because the layout doesn't know what to do with the section.


Solution

  • If a section is declared in a razor view it has to be rendered in the layout.

    I found this in Freeman's Pro ASP.NET MVC 5 book.

    Seems like a bad design to me.