0
votes

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.

2

2 Answers

1
votes

You can indicate that the section is optional by passing false as the second argument:

@RenderSection("HelpLink", false);

Edit: In the case of control flow logic for rendering, you can use .NET in the razor view (like this c# example):

@if(IsSectionDefined("HelpLink"))
{
   @RenderSection("HelpLink", false);
}

Or, if you want to base rendering on whether the user is logged in, you could replace the if logic in the above sample with your security check.

Edit 2:

Make sure you have defined the section:

@section HelpLink {
   //This needs to be defined in any view that uses the layout with the @RenderSection.  It can be empty.
}

Alternatively, you can add the check to see if the section exists and only define the @section in the required view:

if (IsSectionDefined("HelpLink") && User.IsLoggedIn) {

@RenderSection( "HelpLinks", false);

}

0
votes

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.