影响 ASP.NET Core 7 MVC 中所有页面的筛选器

Filter that affects all pages in ASP.NET Core 7 MVC

提问人:ZNAXNOR 提问时间:11/15/2023 最后编辑:ZNAXNOR 更新时间:11/20/2023 访问量:65

问:

我正在 ASP.NET Core 7 中创建一个食谱博客网站。我想在我的网站导航栏上为我的食谱类别(例如:所有食谱、蔬菜食谱或非素食食谱)创建一个过滤器,以便它可以一次影响所有页面,以方便用户体验。这是我的代码-

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>

谢谢。

C# HTML 筛选器 asp.net-core-7.0

评论


答:

0赞 Jalpa Panchal 11/15/2023 #1

FilterViewModel 来存储所选类别:

public class FilterViewModel
{
    public PostCategory? SelectedCategory { get; set; }
}

您必须修改 FilterController 以处理 GET 和 POST 请求。获取凸轮帮助从 ViewModel 中检索所选类别。

public class FilterController : Controller
{
    private readonly ApplicationDbContext _context;

    public FilterController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public IActionResult Index()
    {
        var viewModel = new FilterViewModel
        {
            SelectedCategory = null 
        };

        return View(viewModel);
    }

    [HttpPost]
    public IActionResult Index(FilterViewModel viewModel)
    {
        // You can access the selected category as viewModel.SelectedCategory
        // Perform filtering logic here based on the selected category
        // Update the ViewModel with the filtered results

        return View(viewModel);
    }
}

_TopNavbar.cshtml:

<form asp-controller="Filter" asp-action="Index" id="category" method="post">
    <select class="form-control" asp-for="SelectedCategory" asp-items="@Html.GetEnumSelectList<PostCategory>()" name="SelectedCategory" 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>

_Layout.cshtml:

@{
    var filterViewModel = ViewBag.FilterViewModel as FilterViewModel;
}
0赞 Ruikai Feng 11/15/2023 #2

似乎与这个问题有关?

您可以尝试使用 IMemoryCache 存储帖子

一个最小的例子:

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);
    }
}

在后控制器中:

public async Task<IActionResult> Index()
{
    var cached = _cache.TryGetValue("posts", out var posts);
    if (cached)
    {
        return View(posts);
    }
    return View(await _context.Post.ToListAsync());
}

现在的结果:enter image description here

如果你的帖子会经常更新,或者你只想知道PostCategory,你可以存储在缓存中postCategory

更新: 您可以尝试将枚举转换为字符串并将其存储在缓存中:

 var selected = postCategory.ToString();
 _cache.Set("Selected", selected);
 var selectedincache = _cache.Get("Selected") as string;
 
var postCategoryfromcache = Enum.Parse(typeof(PostCategory), selectedincache);

评论

0赞 ZNAXNOR 11/17/2023
如何保留所选的下拉值?
0赞 Ruikai Feng 11/20/2023
嗨,@ZNAXNOR ,您可以将枚举存储在缓存中时将其转换为 string/int(将其转换为字符串更有意义),我已经更新了相关代码,希望对您有所帮助