Conditionally render MVC layout section

Error:

The following sections have been defined but have not been rendered for the layout page "~/_SiteLayout.cshtml"


Reason:
Let's say there is a Layout as following:

<html>
<head>
</head>
<body>
@RenderBody()
@RenderSection("footer")
</body>
</html>

And a view as following:

<H1>Hello World</H1>

@section footer{
Copyright 2012
}
When rendered,
<h1>Hello World</h1>will be rendered by RenderBody() while Copyright 2012 will be rendered by RenderSection(). But, what if for some reason you want to display footer conditionally on Layout? So for that, if you do something like following, you will encounter an error:

<body>
@RenderBody()
if(condition){
@RenderSection("footer")
}
</body>

Reason is that MVC needs to flush out section declared in your view. Else it displays error as on top of article. To resolve this, there is a quick trick:
<body>
@RenderBody()
if(condition){
@RenderSection("footer") //display
}
else
{
@RenderSection("footer").ToString().Remove(0) //hide
}
</body>

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP