Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5razor-2

Add/remove html markups according to the content of RenderBody()


In my _Layout.cshtml:

<section class="container content-section text-center">
    @RenderBody()
</section>

I only want to have the "section" around when the "body" is not the home page.

I was thinking of detecting url, but soon realized that I will have many Urls bound to the website, it's not the smart way to do it.

So is there anything I could do to make the "section" wrapper smarter enough to know when to appear when not?


Solution

  • You can check that which controller is currently executing its action and put check on HomePage Controller :

    @{
        var controllerName = ViewContext.RouteData.Values["controller"].ToString();
        var actionName = ViewContext.RouteData.Values["controller"].ToString();
    }
    
    @if(controllerName == "HomePage" && actionName == "yourActionName")
    {
    
        @RenderBody()
    
    }
    else
    {
    <section class="container content-section text-center">
    @RenderBody()
    </section>
    }