0

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?

Maciej Miśkiewicz
  • 412
  • 2
  • 8
  • 22
  • 2
    You 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 Answers1

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