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.
2
Answers
FilterViewModel to store the selected category:
You have to modify the FilterController to handle GET and POST request. get cam help retrieve selected category from ViewModel.
_TopNavbar.cshtml:
_Layout.cshtml:
Seems it’s related with this issue?
You could try to store posts with IMemoryCache
a minimal example:
In post controller:
Now the result:
If your posts would be updated frequently or you just want to know PostCategory ,you could store
postCategory
in cache