JesperGJensen
JesperGJensen

Reputation: 423

How can i check if user is logged in from the MVC5 Layout file

I have an MVC 5 Site, using a shared _Layout view. In this _Layout view i render my scripts in the bottom part, after the body.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @*BootStrap must be loaded after JQuery UI in order to override the tooltip function*@
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/Session")

My Problem now, is that i want to include the Session Bundle in every page, except my Login pages. In other words, i want to use the Session Bundle only for pages where the user is logged in and they have an active session.

How can i check for this condition in my _Layout View and render the Script Render conditionally?

In other pages, i would add a bool field to my Model and then use an C# If construction to only render the Script part if true, but i do not have a Model in my _Layout View.

I am also using custom, very simple login methods, so i am not using the Identity Framework of MVC5.

EDIT I was suggested to use the Request object

@if (Request.IsAuthenticated) { @Render...}

This does not work since im using custom login, that does not work with the built in framework. I read up on how this field works, here How does Request.IsAuthenticated work?

The problem is still unresolved

Upvotes: 6

Views: 8788

Answers (2)

JesperGJensen
JesperGJensen

Reputation: 423

I found an Answer.

access session variable from layout page ASP.NET MVC3 RAZOR

I am able to access the Session object from my Layout. Using that, i can check if my custom authentication object is null. If its not null, the user is logged in

@if (Session["BrugerSession"] != null)
{
    @Scripts.Render("~/bundles/Session")
}

Upvotes: 0

jasonwarford
jasonwarford

Reputation: 746

@if (Request.IsAuthenticated)
{
   // Render stuff for authenticated user
}

Upvotes: 11

Related Questions