Maciej Miśkiewicz
Maciej Miśkiewicz

Reputation: 412

MVC Layout.cshtml control

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?

Upvotes: 0

Views: 449

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239460

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.

Upvotes: 1

Related Questions