I am making a MVC application using Entity Framework. In my database I store much information (also about my users). I want my navbar (in Layout) to be different for different users (basing on entities). Normally I pass my entities in controller, but how do I do this with a shared Layout?
Asked
Active
Viewed 441 times
0
-
2You can set a viewbag entry(based on the current user type) and check that in your layout to show different navars – Shyju Dec 27 '16 at 17:00
1 Answers
1
Use child actions:
public class FooController : Controller
{
...
[AllowAnonymous]
[ChildActionOnly]
public ActionResult Navbar()
{
var navbar = // retrieve navbar data
return PartialView("_Navbar", navbar);
}
}
The controller you put this in doesn't matter. You'll just need to reference it when you call the child action. For example, in your layout:
@Html.Action("Navbar", "Foo")
Finally, just create a partial view to render the navbar. In this example, that would be _Navbar.cshtml
. The partial view can utilize a model, and the layout will remain completely agnostic.

Chris Pratt
- 232,153
- 36
- 385
- 444
-
If you call a child action in the layout wouldn't you need it in every controller that uses the layout? – DonO Dec 27 '16 at 20:22
-