How to conditionally render sections in ASP.NET MVC ?
Conditionally render sections in ASP.NET MVC:
bool IsSectionDefined(string name): IsSectionDefined method can be used to check whether the section is defined in the view or not.
In the below example, in the Layout, IsSectionDefined is used to check if the “CustomSection” section is defined in the view. If the “CustomSection” section is defined then it is rendered. And if “CustomSection” section is not defined in the view then default content that is present in the Layout will be displayed.
_Layout.cshtml content:
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title - TechCartNow.com</title> </head> <body> <div class="container body-content"> @RenderBody() @*Returns a value that indicates whether the specified section is defined in the page.*@ @if (IsSectionDefined(name: "CustomSection")) { // In layout pages, renders the content of a named section and specifies whether // the section is required. @RenderSection(name: "CustomSection") <p>Custom section content.</p> } else { <p><b>Default content.</b></p> } </div> </body> </html>
Index.cshtml content with CustomSection :
CustomSection content will be displayed.
@{ ViewBag.Title = "Index Page with CustomSection"; } <p>Index page content.</p> @section CustomSection { <p><b>Custom view content.</b></p> }
Output:
About.cshtml content without CustomSection :
Default content specified in the Layout will be displayed.
@{ ViewBag.Title = "About Us Page without CustomSection"; } <p>About us page content.</p>
Output:
.NET Professional | Microsoft Certified Professional | DZone’s Most Valuable Blogger | Web Developer | Author | Blogger
Doctorate in Computer Science and Engineering
Microsoft Certified Professional (MCP) with over 12+ years of software industry experience including development, implementation & deployment of applications in the .NET framework
Experienced and skilled Agile Developer with a strong record of excellent teamwork, successful coding & project management. Specialises in problem identification and proposal of alternative solutions. Provided knowledge and individual mentoring to team members as needed
Among top 3% overall in terms of contribution on Stack Overflow (~2.3 million people reached my posts). Part of the top 1% Stack Overflow answerers in ASP.NET technology.
DZone’s Most Valuable Blogger (MVB)
Created and actively maintain the TechCartNow.com tech blog while also editing, writing, and researching topics for publication.
Excellent skills in Application Development using C#/Vb.Net, .NET Framework, ASP.NET, MVC, ADO.NET, WCF, WPF, Web API, SQL Server, jQuery, Angular, React, BackboneJS