Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 985
HP200104 Avatar asked Sep 05 '25 03:09

HP200104


2 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>
    }
    
like image 73
Matthew M. Avatar answered Sep 07 '25 20:09

Matthew M.


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).

like image 34
Mike Brind Avatar answered Sep 07 '25 19:09

Mike Brind