Getting data into a partial view or layout using MVC

asp.net-mvc

Solution

I would suggest you can go for a child action and invoke it from the layout, By this way you can avoid carry out the information in all the view models.

Ex.

Child action

public class UserController
{
  [ChildActionOnly]
  public PartialViewResult UserInfo()
  {
     var userInfo = .. get the user information from session or db

     return PartialView(userInfo);
  }
}

Partial View

@model UserInfoModel

@Html.DisplayFor(m => m.UserName)
@Html.DisplayFor(m => m.CompanyName)
...

Layout view

<header>
  @Html.Action("UserInfo", "User")
</header>

Problem

I want to display information about the logged in user (username, company name, number of notifications, etc) in the layout and/or partial views. These will be common on every page. Is there a trick for getting this data to them, or is it a case of extending each model to have this information in them?

Original source