MuriloKunze
MuriloKunze

Reputation: 15573

How to use a model in layoutpage

I'm trying to create a menu which is shown when the user is logged in.. the code is something like this:

<html>
<body>
     @if(Model.IsUserLogged){
     //some html
     }

     @RenderBody()

     @if(Model.IsUserLogged){
     //some html again
     }
</body>
</html>

but in layout page I can't use a model, so, what's the best way to do this?

Upvotes: 1

Views: 71

Answers (2)

kprobst
kprobst

Reputation: 16651

There's a way to do this that involves using a partial view, although you'd need to move your logic there and out of the layout. Create a partial view (say, "_MyMenu" or whatever), place your rendering logic there, create a controller method for it:

public PartialViewResult MenuView() {
    SomeObject model = GetSomeObject()
    return PartialView("_MyMenu", model);
}

Then in your layout page, call it with RenderAction:

@{Html.RenderAction("MenuView", "MyController");}

Someone already mentioned how to obtain the user's authentication state, so I'm not sure if that's enough for you.

Upvotes: 1

dove
dove

Reputation: 20674

If it is authorization or authentication information you are looking for why not read from Request or cookies. For example above:

@Request.IsAuthenticated  

Other small amounts of user data could be stored in a cookie and read using a helper. Or you could have much more user data in local storage if your audience browsers could support it.

Upvotes: 1

Related Questions