Umair Arif
Umair Arif

Reputation: 117

Get Data from DB in Layout page in ASP.NET MVC

I want to load data in navbar after fetching data from DB in Layout.cshtml page in ASP.NET MVC. But I am facing a Problem that how to fetch data in layout page as there is no Controller unlike Code Behind file in Web Forms. Anyone please help me that: - How to store data in Data Model - How to pass it to Layout page Thanks in advance.

Upvotes: 3

Views: 4546

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

Use a child action:

public class FooController : Controller
{
    ...

    [ChildActionOnly]
    public ActionResult NavBar()
    {
        var navbar = // query your database;
        return PartialView("_NavBar", navbar);
    }
}

Then create the partial view Views\Shared\_NavBar.cshtml and put the HTML for it there. Your model will be what you queried from the database in the child action.

Finally in your layout:

@Html.Action("NavBar", "Foo")

Upvotes: 8

Related Questions