Search code examples
c#asp.net-corerazor-pages

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.


Solution

  • 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>
      }