0

I'm writing an Asp.net MVC application (my first MVC app). I need to pass data to the _Layout view to customize the header and footer on my pages - which user is logged in, if they have any notifications, etc. The _Layout page always needs this information, but the child pages do not.

How should I pass this data to the view? Can I create a LoggedInUser property that the view can access, in the same way there is a Model and ViewBag? LoggedInUser could be populated by the base controller class.

Or is there a better way to implement this?

Oliver
  • 11,297
  • 18
  • 71
  • 121

2 Answers2

1

To detect authentication:

User.Identity.IsAuthenticated

Then you can use sections ASP.NET MVC 3: Layouts and Sections with Razor or/and @Html.RenderAction (Html.RenderAction and Html.Action)

webdeveloper
  • 17,174
  • 3
  • 48
  • 47
1

If you're using MembershipProvider and/or RoleProvider you can do as webdeveloper pointed out to get the identity of the current user User.Identity.Name, if showing it's name is what you want.

Also you could type your _layout to use a specific model, but I don't recommend it. See this question's answer for further details.

Lastly you could populate a ViewBag property on your controllers to have the user information you need.

I wanted to point out that you could do a partial view to achieve this, and avoid _layout typing and populating the ViewBag on each request.

Community
  • 1
  • 1
Esteban
  • 3,108
  • 3
  • 32
  • 51
  • Thanks, I initially had settled on inheriting all from one ViewModel and typing the _Layout, but I'll looking into partial views instead. – Oliver Sep 27 '12 at 14:51