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.
You have a couple of options:
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>
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With