I am creating a Recipe Blog Website in ASP.NET Core 7. I want to create a filter for my recipe category (eg: All recipes, Veg recipes or NonVeg recipes) on my website navbar so that it can affect all the pages at once for the ease of user experience. Here is my code-
FilterController.cs
:
public class FilterController : Controller
{
private readonly ApplicationDbContext _context;
public FilterController(ApplicationDbContext context)
{
_context = context;
}
[HttpPost]
public async Task<IActionResult> Index(PostCategory? postCategory)
{
var post = from p in _context.Posts select p;
// Category Dropdown
if (postCategory != null)
{
post = _context.Posts.Where(c => c.PostCategory == postCategory);
}
return View(await post.ToListAsync());
}
}
_TopNavbar.cshtml
:
<nav class="navbar navbar-expand navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 ps-10 fixed-top">
<div class="container-fluid">
<!--Options-->
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between ps-3">
<!-- Dropdown -->
<div class="col-4">
<form asp-controller="Filter" asp-action="Index" id="category">
<select class="form-control" asp-items="@Html.GetEnumSelectList<PostCategory>()" name="postCategory" id="post-filter">
<option value="">All</option>
</select>
<button class="btn btn-outline-success me-2" type="submit">Search</button>
<a class="btn btn-outline-danger" asp-area="" asp-controller="Post" asp-action="Index">Reset</a>
</form>
</div>
</div>
</div>
</nav>
Thank you.
Seems it's related with this issue?
You could try to store posts with IMemoryCache
a minimal example:
public class FilterController : Controller
{
private readonly IMemoryCache _cache;
private readonly ApplicationDbContext _context;
public FilterController(ApplicationDbContext context, IMemoryCache cache)
{
_context = context;
_cache = cache;
}
[HttpPost]
public async Task<IActionResult> Index(PostCategory? postCategory)
{
List<Post> posts;
if (postCategory != null)
{
posts = _context.Post.Where(c => c.PostCategory == postCategory).ToList();
}
else
{
posts = _context.Post.ToList();
}
_cache.Set("posts", posts);
return View(posts);
}
}
In post controller:
public async Task<IActionResult> Index()
{
var cached = _cache.TryGetValue("posts", out var posts);
if (cached)
{
return View(posts);
}
return View(await _context.Post.ToListAsync());
}
If your posts would be updated frequently or you just want to know PostCategory ,you could store postCategory
in cache
Update: You could try convert the enum to string and store it in cache:
var selected = postCategory.ToString();
_cache.Set("Selected", selected);
var selectedincache = _cache.Get("Selected") as string;
var postCategoryfromcache = Enum.Parse(typeof(PostCategory), selectedincache);