I am creating a dropdown ( that uses a database table ) for my Navbar which is located in my Shared View.
I was initializing a List<> from my FilterViewModel
in FilterController
, then using the initialized variable in my Shared View. It gave me an error as no variable was initialized in my IndexController
.
After initializing the variable in IndexController
, the website finally launched but I was unable to open any other pages ( as the List<> variable was not initialized in their controller files ). It seems that I have to initialize the variable in all my controller files before using it globally in my Shared View for it to work properly without any errors.
How can I initialize the variable globally without it being so tedious and potentially harmful for my website in the future.
Here is my code-
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);
}
Thank you.
I suggest you could consider querying the list when the application started(if this value will not changed) and then storing it inside the memory cache.
Then when you want to use it, you could directly get it from the memory cache instead of querying it again.
You could also put it inside the Redis or other memory cache which is dependent on your requirement.
More details, you could refer to below example:
Put below codes inside the 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.)
}
}
Inside the shared view:
@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>
Result: