How to add dynamic content to a _Layout.cshtml file?

Viewed 454

I am developing a web application in ASP.NET Core and I wanted to know if there was a way to dynamically update content in the _Layout.cshtml file from data that I am calling from a MySQL database like you would do with a normal Razor page and Model, e.g. Index.cshtml and Index.cshtml.cs

Code I want to access in _Layout.cshtml (I'm not sure where to add this code):

public List<Location> activeLocation = new List<Location>();

        public void OnGet()
        {

            activeLocation = new Inventory().ActiveLocation;

        }

_Layout.cshtml (where I want to access the data):

@foreach(var location in Model.activeLocation)
            {
                    <div class="location_name">@location.Name</div>
            }

I have tried adding C# code inside the _Layout.cshtml file to see if I was able to call the data from the MySQL database but it was giving a lot of errors.

3 Answers

You have a couple of options:

  1. Put it right in the Razor page (_Layout.cshtml)

    @{
        List<string> GetLocations()
        {
            // e.g. Put a database call here
    
            return new List<string>()
            {
                "Texas",
                "Connecticut",
                "Florida"
            };
        }
    }
    
    @foreach (var location in GetLocations())
    {
        <div class="location_name">@location</div>
    }
    
  2. Call it from a class:

    public static class Locations
    {
        public static List<string> GetLocations()
        {
            // e.g. Put a database call here
    
            return new List<string>()
            {
                "Texas",
                "Connecticut",
                "Florida"
            };
        }
    }
    
    @foreach (var location in Locations.GetLocations())
    {
        <div class="location_name">@location</div>
    }
    

The view component (https://www.learnrazorpages.com/razor-pages/view-components) is designed for adding dynamic content to layout pages. They centralise the logic and view for a segment of UI so that you don't have to make database calls directly from a Razor file (always a bad idea) or have to add the same code to every page that makes use of the layout (not scalable).

Maybe you can try to use ViewData:

Layout:

@{
    var activeLocation=ViewData["activeLocation"] as List<Location>;
}
@foreach(var location in activeLocation)
            {
                    <div class="location_name">@location.Name</div>
            }

and then you can set ViewData["activeLocation"] in OnGet() of each page which uses the layout,so that you can set different content for different pages with the layout:

public void OnGet()
        {
            ViewData["activeLocation"] = new List<Location> {... };
        }
Related