我正在为我的导航栏创建一个下拉菜单(使用数据库表),它位于我的共享视图中。
我正在从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);
}
谢谢你。
我建议你可以考虑在应用程序启动时查询该列表(如果该值不会改变),然后将其存储在内存缓存中。
那么当你想使用它的时候,你可以直接从内存缓存中获取它,而不用再次查询。
您也可以将其放入 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">
© 2023 - CoreMVCIdentity - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
<h1>
@filterVM.PostCategories.FirstOrDefault().FirstName.ToString()
</h1>
</footer>
结果: