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:

Index.cshtml content with CustomSection :

CustomSection content will be displayed.




About.cshtml content without CustomSection :

Default content specified in the Layout will be displayed.


Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone's Most Valuable Blogger (MVB)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *