gpt4 book ai didi

c# - 如何将动态内容添加到 _Layout.cshtml 文件?

转载 作者:行者123 更新时间:2023-12-05 04:32:15 27 4
gpt4 key购买 nike

我正在 ASP.NET Core 中开发一个 Web 应用程序,我想知道是否有一种方法可以根据我从 MySQL 数据库调用的数据动态更新 _Layout.cshtml 文件中的内容,就像您使用普通 Razor 页面和模型,例如Index.cshtml 和 Index.cshtml.cs

我想在 _Layout.cshtml 中访问的代码(我不确定在哪里添加这段代码):

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

public void OnGet()
{

activeLocation = new Inventory().ActiveLocation;

}

_Layout.cshtml(我想访问数据的地方):

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

我尝试在 _Layout.cshtml 文件中添加 C# 代码,看看我是否能够从 MySQL 数据库中调用数据,但它给出了很多错误。

最佳答案

你有几个选择:

  1. 将其放在 Razor 页面 (_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. 从类中调用它:

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

关于c# - 如何将动态内容添加到 _Layout.cshtml 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71698987/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com