I have a posts category on my website. I have created a dropdown filter that filters my posts according to the chosen category.
The filter was created as a controller action method, but I want to make it global.
Here is the filter code - FilterController.cs
:
public async Task<IActionResult> Index(string postCategory)
{
ViewBag.PostCategory = postCategory;
var filteredPost = from p in _context.Posts select p;
if (postCategory == "All")
{
filteredPost = _context.Posts;
}
else if (!string.IsNullOrEmpty(postCategory))
{
filteredPost = filteredPost.Where(p => p.PostCategory == postCategory);
}
var filteredCategory = new CardsViewModel
{
PostCard = await filteredPost.ToListAsync()
};
_cache.Set("filteredCategory", filteredCategory);
string url = Request.Headers["Referer"].ToString();
return Redirect(url);
}
Currently, all controllers rely on _context.Posts
to display data. The code filters _context.Posts
inside filteredPost
according to the user-selected category. I want to use the filteredPost
instead of _context.Posts
in my controllers. How can I achieve this?
Example of a controller where I want to use filteredPost
instead of _context.Posts
:
[HttpGet]
public async Task<IActionResult> Index()
{
return View(await _context.Posts.ToListAsync());
}
All advice is appreciated. Thank you.
Don't think of it in terms of a "global filter" - that's not how web-application frameworks (well) work.
I don't recommend using a shared/common
Controller
subclass: that'll only cause problems in the long-term; fortunately, all you need is a few extension-methods:So then in any
Controller
of yours, all you need to do is (for example):Note that the
MyDbContext
is scoped per request, so theMyDbContext
returned fromHttpContext.RequestServices
is the same instance asExampleController.dbContext
.