Home > Net >  How to add dynamic content to a _Layout.cshtml file?
How to add dynamic content to a _Layout.cshtml file?

Time:04-01

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

CodePudding user response:

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 >@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 >@location</div>
    }
    

CodePudding user response:

Maybe you can try to use ViewData:

Layout:

@{
    var activeLocation=ViewData["activeLocation"] as List<Location>;
}
@foreach(var location in activeLocation)
            {
                    <div >@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