在 ASP.NET Core MVC 中的共享页面中声明全局变量

问题描述 投票:0回答:1

我正在为我的导航栏创建一个下拉菜单(使用数据库表),它位于我的共享视图中。

我正在从FilterViewModel中的

FilterController
初始化
List<>
,然后在我的共享视图中使用初始化的变量。它给了我一个错误,因为我的
IndexController
中没有初始化变量。

IndexController
中初始化变量后,网站终于启动了,但我无法打开任何其他页面(因为List<>变量在其控制器文件中未初始化)。看来我必须在我的共享视图全局使用它之前在所有控制器文件中初始化该变量,才能使其正常工作而不会出现任何错误。

我怎样才能初始化变量全局,而不会让它变得如此乏味并且将来可能对我的网站有害。


这是我的代码-

  • 视图模型:
public class FilterViewModel
{
    public List<PostCategoryModel>? PostCategories { get; set; }
}
  • 控制器
public async Task<IActionResult> Index()
{
    var FilterVM = new FilterViewModel
    {
        PostCategories = await _context.PostCategories.ToListAsync()
    };

    return View(FilterVM);
}

谢谢你。

c# asp.net-core-mvc global-variables master-pages
1个回答
0
投票

我建议你可以考虑在应用程序启动时查询该列表(如果该值不会改变),然后将其存储在内存缓存中。

那么当你想使用它的时候,你可以直接从内存缓存中获取它,而不用再次查询。

您也可以将其放入 Redis 或其他内存缓存中,具体取决于您的要求。

更多详情,您可以参考下面的例子:

将以下代码放入program.cs中

// Load and cache data
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var context = services.GetRequiredService<ApplicationDbContext>();
        var cache = services.GetRequiredService<IMemoryCache>();

        //load the data
        var postCategories = context.Employees.ToList();
        var filterVM = new FilterViewModel { PostCategories = postCategories };

        
        cache.Set("FilterData", filterVM);
    }
    catch (Exception ex)
    {
        // Handle exceptions (logging, etc.)
    }
}

在共享视图内:

@using Microsoft.Extensions.Caching.Memory;
@inject IMemoryCache Cache
@{
    if (!Cache.TryGetValue("FilterData", out FilterViewModel filterVM))
    {
         filterVM = new FilterViewModel();  
    }
}

<footer class="border-top footer text-muted">
    <div class="container">
        &copy; 2023 - CoreMVCIdentity - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
    </div>
    <h1>
        @filterVM.PostCategories.FirstOrDefault().FirstName.ToString()

    </h1>
</footer>

结果:

© www.soinside.com 2019 - 2024. All rights reserved.