Reputation: 15003
This is probably a basic question, but so far I can not figure out how to solve this probably.
I have a _Layout.cshtml
which has some markup to describe which user is logged in. This information is stored in my database, so I need to retrieve this on all my views.
My application contains a lot of views and this information needs to be displayed on all pages.
How do I solve this, without having to get this information on all my controllers?
Update, my solution was this, using @Jayesh Goyani guidance:
[ChildActionOnly]
public async Task<ActionResult> GetDashboardView()
{
var model = new DashboardModel();
/* fill model from database */
return model != null ? PartialView("_DashboardView", model) : null;
}
With an _DashboardView
located in my /Views/Dashboard/_DashboardView.cshtml
:
@model DashboardViewModel
<p>@Model.MyProperty</p>
And used like this in my _Layout.cshtml
:
@{Html.RenderAction("GetDashboardView", "Dashboard");}
Upvotes: 1
Views: 251
Reputation: 11154
The right way is to call Html.RenderAction() inside the layout file, where you want the user-specific details. Then create a suitable Action method somewhere which reads the user's account details and returns them as a view (partial view) or as raw html (return Content("...")).
That way, you can also benefit the ability to cache the layout page and keep the user's account details region uncached (since it's obviously different for every user).
Setting a ViewBag is not a good idea, it's not strongly type and it breaks the correct schema of MVC. By using Filtering in ASP.NET MVC you can add the user detail into viewbag on every request.
Upvotes: 2