Search code examples
asp.net-coreasp.net-core-mvc

Hide Nav and footer while user is logged in ASP.NET Core


@{
    Layout = null;
}

The above code hides the nav and footer and remove the whole css.

User.Identity.IsAuthenticated

If I am using this synapsis, it will not show the nav and footer.

Could anybody will give me a solution for this problem?

I need to show the navigation bar and footer after the login or sign. If I am in the login and signup page it won't.


Solution

  • Generally, you should have different layouts for anonymous and login users (pages). This will make it easier to structure the template for the pages with different user scenarios instead of manipulating them in one layout.

    With different layouts, you can render the required stylesheets, scripts, and the HTML section(s).

    _LayoutAnonymous.cshtml

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - My ASP.NET Application</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="container body-content">
            @RenderBody()
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
    

    _Layout.cshtml

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - My ASP.NET Application</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <!-- Nav section -->
        <div class="container body-content">
            @RenderBody()
            <hr />
            <!-- Footer section -->
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
    

    On your Login and Signup page, you specify the layout used as:

    @{
        Layout = "~/Views/Shared/_LayoutAnonymous.cshtml";
    }
    

    While for the other page that only accessible after login, you specify the layout used as:

    @{
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    

    Reference: What is Layout View in ASP.NET MVC