I just got some error that I don’t expected to see…
To be clear, I’ll show working code and code with error:
This is working
_MainLayout.cshtml
<div id="content">
<h1>@Page.Title</h1>
@RenderSection("left", false)
@RenderBody()
</div>
Page.cshtml
@section left{
<p>Some text on left side</p>
}
<div>
Some content
</div>
In this case everything works fine, but when I deleted @RenderSection("left", false) inside the _MainLayout.cshtml I get the exception! Which case do I need it? See example below:
This is not working
_MainLayout.cshtml
@if (WebSecurity.IsAuthenticated) {
<h1>@Page.Title</h1>
@RenderSection("left", false)
@RenderBody()
} else {
<h1>You not logged in!</h1>
<p>To see this page, you have to login first.</p>
}
Page.cshtml
@section left{
<p>Some text on left side</p>
}
<div>
Some content
</div>
In this case, if user is not authenticated, I have this exception:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Следующие разделы были определены, но не были обработаны для страницы макета "~/_MainLayout.cshtml": "left".
Which can be translated as: Section was created but wasn't rendered for layout page "~/_MainLayout.cshtml": "left".
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Следующие разделы были определены, но не были обработаны для страницы макета "~/_MainLayout.cshtml": "left".]
System.Web.WebPages.WebPageBase.VerifyRenderedBodyOrSections() +91298
System.Web.WebPages.WebPageBase.PopContext() +332
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +95
System.Web.WebPages.<>c__DisplayClass7.<RenderPageCore>b__6(TextWriter writer) +102
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +12
System.Web.WebPages.WebPageBase.Write(HelperResult result) +67
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +66
System.Web.WebPages.WebPageBase.PopContext() +262
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +95
System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContext context) +249
The question is: how can I make it work?
Any advice is valuable!
The problem is that you’re still declaring the section in your child view, and the razor rendering engine doesn’t know what to do with it.
I’m not sure what the best way to deal with it would be some possible workarounds are:
RenderSection("left", false)outside of the body of theifblock.