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?
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
_layoutto 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
_layouttyping and populating the ViewBag on each request.