如何在 ASP.NET Core 6 中过滤产品而不重新加载页面

问题描述 投票:0回答:1

当用户位于产品类别页面时,我尝试按品牌过滤产品数据。这里的景色product category。所以,我想通过左侧边栏按品牌进行过滤。我使用ajax,这样每次用户在品牌按钮中选择时就无法重新加载页面。

这是代码:

@{
    ViewData["Title"] = "ProductCategory";
    Layout = "~/Views/Layout/_CategoryLayout.cshtml";
}
@{
    IEnumerable<Category> categories = ViewBag.Categories as IEnumerable<Category>;
    IEnumerable<Brand> brands = ViewBag.Brand as IEnumerable<Brand>;
    string currentUrl = Context.Request.GetDisplayUrl();
}
<input type="hidden" id="category-id" value="@Model.FirstOrDefault().CategoryId" />

<!-- SECTION -->
<div class="section">
    <!-- container -->
    <div class="container">
        <!-- row -->
        <div class="row">
            <!-- ASIDE -->
            <div id="aside" class="col-md-3">
                <!-- aside Widget -->
                <div class="aside">
                    <h3 class="aside-title">Brands</h3>
                    <div class="checkbox-filter">
                        @foreach (var item in brands)
                        {
                            <div class="input-checkbox">
                                <input type="checkbox" class="brand-checkbox" name="brand" id="@item.BrandId">
                                <label for="@item.BrandId">
                                    <span></span>
                                    @item.BrandName
                                    <small>(@item.Products.Count)</small>
                                </label>
                            </div>
                        }
                    </div>

                </div>
                <!-- /aside Widget -->
                <!-- aside Widget -->
                <div class="aside">
                    <h3 class="aside-title">Price</h3>
                    <div class="price-filter">
                        <div id="price-slider"></div>
                        <div class="input-number price-min">
                            <input id="price-min" type="number">
                            <span class="qty-up">+</span>
                            <span class="qty-down">-</span>
                        </div>
                        <span>-</span>
                        <div class="input-number price-max">
                            <input id="price-max" type="number">
                            <span class="qty-up">+</span>
                            <span class="qty-down">-</span>
                        </div>
                    </div>
                </div>
                <!-- /aside Widget -->
                
            </div>
            <!-- /ASIDE -->
            <!-- STORE -->
            <div id="store" class="col-md-9">
                <!-- store top filter -->
                <div class="store-filter clearfix">
                    <div class="store-sort">
                        @* <label>
                            Sort By:
                            <select class="input-select">
                                <option value="0">Popular</option>
                                <option value="1">Position</option>
                            </select>
                        </label>

                        <label>
                            Show:
                            <select class="input-select">
                                <option value="0">20</option>
                                <option value="1">50</option>
                            </select>
                        </label> *@
                    </div>
                    <ul class="store-grid">
                        <li class="active"><i class="fa fa-th"></i></li>
                        <li><a href="#"><i class="fa fa-th-list"></i></a></li>
                    </ul>
                </div>
                <!-- /store top filter -->
                <!-- store products -->
                <div class="row">
                    <!-- product -->
                    @foreach (var item in Model.Take(6))
                    {
                        <div class="col-md-4 col-xs-6">
                            <div class="product">
                                <a href="/post/@SlugGenerator.SlugGenerator.GenerateSlug(item.ProductName)[email protected]().ProductVariations.FirstOrDefault().ProductVarId" />
                                <div class="product-img">

                                    <img src="~/Contents/img/@item.ProductItems.FirstOrDefault().Image1" width="200" height="200" alt="">
                                        <div class="product-label">
                                            <span class="sale">-30%</span>
                                            <span class="new">NEW</span>
                                        </div>
                                    </div>
                                    <div class="product-body">
                                    @*  <p class="product-category">@item.Category.CategoryName.ToUpper()</p> *@
                                        <h3 class="product-name"><a href="#">@item.ProductName.ToUpper()</a></h3>
                                        <h4 class="product-price">[email protected]<del class="product-old-price">@* $@(item.Product.Price + 200) *@</del></h4>
                                        <div class="product-rating">
                                            <i class="fa fa-star"></i>
                                            <i class="fa fa-star"></i>
                                            <i class="fa fa-star"></i>
                                            <i class="fa fa-star"></i>
                                            <i class="fa fa-star"></i>
                                        </div>
                                        <div class="product-btns">
                                            <button class="add-to-wishlist"><i class="fa fa-heart-o"></i><span class="tooltipp">add to wishlist</span></button>
                                            <button class="add-to-compare"><i class="fa fa-exchange"></i><span class="tooltipp">add to compare</span></button>
                                            <button class="quick-view"><i class="fa fa-eye"></i><span class="tooltipp">quick view</span></button>
                                        </div>
                                    </div>
                    
                            </div>
                        </div>
                    }
                    <!-- /product -->
                </div>
                <!-- /store products -->
                <!-- store bottom filter -->
                <div class="store-filter clearfix">
                    <span class="store-qty">Showing 20-100 products</span>
                    <ul class="store-pagination">
                        <li class="active">1</li>
                        <li><a href="#">2</a></li>
                        <li><a href="#">3</a></li>
                        <li><a href="#">4</a></li>
                        <li><a href="#"><i class="fa fa-angle-right"></i></a></li>
                    </ul>
                </div>
                <!-- /store bottom filter -->
            </div>
            <!-- /STORE -->
        </div>
        <!-- /row -->
    </div>
    <!-- /container -->
</div>
<!-- /SECTION -->

每次用户点击选择时,Ajax 代码都会过滤品牌:

@section Scripts {
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const checkboxes = document.querySelectorAll('.brand-checkbox');

            checkboxes.forEach((checkbox) => {
                checkbox.addEventListener('change', function () {
                    // Ensure only one checkbox is checked at a time
                    checkboxes.forEach((otherCheckbox) => {
                        if (otherCheckbox !== this) {
                            otherCheckbox.checked = false;
                        }
                    });

                    // If a checkbox is checked, get its value, otherwise set to null
                    var selectedBrand = this.checked ? this.id : null;
                    var categoryId = $('#category-id').val();

                    $.ajax({
                        url: '@Url.Action("FilterByBrands", "ProductView")',
                        type: 'GET',
                        data: { brandid: selectedBrand, cateid: categoryId },
                        success: function (response) {
                            $('#product').html(response);
                        }
                    });
                });
            });
        });
    </script>
}

这是控制器的代码:

[HttpGet]
public ActionResult FilterByBrands(int brandid, int cateid)
{
    ViewBag.Brand = _context.Brands.Include(n => n.Products).ToList();

    var product = _context.Products
                          .Where(n => n.BrandNavigation.BrandId == brandid 
                                      && n.CategoryId == cateid)
                          .Include(n => n.ProductItems)
                          .ThenInclude(n => n.ProductVariations)
                          .Include(n => n.Category)
                          .ToList();

    return PartialView("_FilterPartial",product);
}

_FilterPartial
视图与我上面提到的产品类别相同,也是代码。

我认为 Ajax 工作正常,因为每次我选择品牌按钮并打开网站网络并选择 Fetch/XHR。服务器像这样为我返回Fetch/XHR,当我单击它时,它会为我打开一个像这样的视图view

有人知道问题所在吗?我不想重新加载页面,但似乎返回了其他内容。我真的很感谢任何指示。

谢谢你

c# ajax asp.net-core asp.net-ajax
1个回答
0
投票

当用户位于产品类别页面时,尝试按品牌过滤产品数据。

使用 Ajax 或 Fetch API 从 HTML 客户端向后端发出请求,返回部分视图,然后在成功回调函数中更新目标 html 内容,这是动态更新视图页面而无需重新加载的常用方法。

我认为 Ajax 工作正常,因为每次我选择品牌按钮并打开网站网络并选择 Fetch/XHR。服务器像这样为我返回Fetch/XHR,当我单击它时,它会为我打开一个像这样的视图view

我认为您的请求返回的是按品牌过滤的产品的预期部分视图内容,要更新 html 内容,我们只需要设置返回响应的目标 html 容器即可。

根据您的代码,我们可以发现您使用 id 选择器

$('#product').html(response);
来更新视图页面,但我们在您的视图页面中找不到带有
id="product"
的 html 元素。

根据您的html结构,您可以尝试修改以下代码,以更新产品的父html容器。

//...
success: function (response) {
    $('#store .row').html(response);
    //...
 
© www.soinside.com 2019 - 2024. All rights reserved.