页面刷新后如何存储 JS 选择数据

How to store JS selection data after page refresh

提问人:Onur Serbes 提问时间:10/26/2023 最后编辑:Onur Serbes 更新时间:10/31/2023 访问量:60

问:

我正在尝试创建一个电子商务页面。我想使用复选框进行类别选择。它可以进行过滤并为我提供必要的数据;后端工作。但是当我更改页面(分页功能)时,类别选择会丢失。所以数据不再稳定了。该列表再次为我提供了默认的 SQL 查询。我怎样才能让它稳定?如何存储我的选择?

编辑(如果我使用localStorage,则会出现问题,根据答案)如果我需要举个例子来确保你更好地理解。您的数据中有 10 个项目,每个项目显示 6 个,当您切换到第二页时,您需要查看其余 4 个数据。我的问题发生在这里,我没有看到其余的 4 个数据。我在每个页面中再次看到前 6 个。我看到剩下的 4 个数据(一秒钟),然后我立即看到前 6 个数据。

如果需要更多代码块,我可以编辑帖子

控制器

[Authorize]
public async Task<IActionResult> Index(GetECommerceIndexQuery request, List<int> categoryIds)
{
    var result = await MediatrSend(request);
    return View(result);
}

[Authorize]
[HttpPost]
public async Task<IActionResult> GetCategories([FromBody] List<int> selectedIds)
{
    var result = await MediatrSend(new GetECommerceIndexQuery { CategoryIds = selectedIds});
    return Json(result);
}

查询文件

 public class GetECommerceIndexQuery : MediatR.IRequest<ECommerceListDTO>
    {
        public ClaimModel ClaimModel { get; set; }
        public List<int> CategoryIds { get; set; }
        public int Page { get; set; } = 1;
        public int PageSize { get; set; } = 6;
    }

    public class GetECommerceIndexQueryHandler : IRequestHandler<GetECommerceIndexQuery, ECommerceListDTO>
    {
        private readonly IECommerceProductRepository _eCommerceProductRepository;

        public GetECommerceIndexQueryHandler(IECommerceProductRepository eCommerceProductRepository)
        {
            _eCommerceProductRepository = eCommerceProductRepository;
        }
        public async Task<ECommerceListDTO> Handle(GetECommerceIndexQuery request, CancellationToken cancellationToken)
        {
            ECommerceListDTO response = new ECommerceListDTO();

            int page = request.Page;
            int pageSize = request.PageSize;

            var products = await _eCommerceProductRepository.GetECommerceProductList(request.CategoryIds);

            var totalProducts = products.Count();
            var totalPages = (int)Math.Ceiling((double)totalProducts / pageSize);
            var paginatedProducts = products.Skip((page - 1) * pageSize).Take(pageSize);

            response.MetaData = new DatatableMetaDTO
            {
                page = page,
                pages = totalPages,
                perpage = pageSize,
                total = totalProducts,
            };

            response.ProductData = paginatedProducts;
            response.CategoryData = await _eCommerceProductRepository.GetECommerceCategoryList();

            return response;
        }
    }

分页

 <!-- Pagination Buttons -->
                            <div class="d-flex justify-content-center">
                                <ul class="pagination">
                                    @for (int i = 1; i <= Model.MetaData.pages; i++)
                                    {
                                        <li class="page-item @(i == Model.MetaData.page ? "active" : "")">
                                            <a class="page-link" href="@Url.Action("Index", new { page = i })">@i</a>
                                        </li>
                                    }
                                </ul>
                            </div>

脚本

@section scripts {
    <script>
        $(document).ready(function () {
            $(".checkbox-item").click(function () {
                var selectedValues = $(".checkbox-item:checked").map(function () {
                    return parseInt(this.value, 10);
                }).get();

                var jsonData = JSON.stringify(selectedValues);

                $.ajax({
                    url: '@Url.Action("GetCategories", "ECommerce")',
                    type: 'POST',
                    data: jsonData,
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        console.log(data);
                        renderProducts(data.ProductData);
                    },
                    error: function (error) {
                        console.error('Error Occurred:', error);
                    }
                });
            });

            function renderProducts(products) {
                $('#productContainer').empty();

                $.each(products, function (index, product) {
                    var productUrl = '@Url.Action("ProductDetail", new { id = 0 })'.replace("0", product.Id);

                    var productHtml = `
                                <div class="col-md-4 col-lg-12 col-xxl-4">
                                    <a href="${productUrl}" class="product-link">
                                        <div class="card card-custom gutter-b card-stretch">
                                            <div class="card-body d-flex flex-column rounded bg-light justify-content-between">
                                                <div class="text-center rounded mb-7">
                                                    <img src="assets/media/products/${product.ProductName}" class="mw-100 w-200px" alt="${product.ProductName}">
                                                </div>
                                                <div>
                                                    <h4 class="font-size-h5">
                                                        <span class="text-dark-75 font-weight-bolder">${product.ProductName}</span>
                                                    </h4>
                                                    <div class="font-size-h6 text-muted font-weight-bolder">${product.Price}</div>
                                                </div>
                                            </div>
                                        </div>
                                    </a>
                                </div>`;

                    $('#productContainer').append(productHtml);
                });
            }
        });
    </script>
}
asp.net ASP.Net-Core Razor 分页 筛选

评论


答:

1赞 Jalpa Panchal 10/27/2023 #1

要解决在更改页面时丢失类别选择并在每个页面上看到相同数据的问题,您可以按照以下更新的代码进行操作:

@section scripts {
    <script>
        $(document).ready(function () {
            var selectedCategories = JSON.parse(localStorage.getItem('selectedCategories')) || [];
            var currentPage = parseInt(localStorage.getItem('currentPage')) || 1;
            
            $(".checkbox-item").each(function() {
                var value = parseInt($(this).val(), 10);
                if (selectedCategories.includes(value)) {
                    $(this).prop('checked', true);
                }
            });

            loadProducts();

            $(".checkbox-item").click(function () {
                updateSelectedCategories();
                currentPage = 1; 
                localStorage.setItem('currentPage', currentPage);
                loadProducts();
            });

            $(".page-link").click(function (e) {
                e.preventDefault();
                currentPage = parseInt($(this).text(), 10);
                localStorage.setItem('currentPage', currentPage);
                loadProducts();
            });

            function updateSelectedCategories() {
                selectedCategories = $(".checkbox-item:checked").map(function () {
                    return parseInt(this.value, 10);
                }).get();
                localStorage.setItem('selectedCategories', JSON.stringify(selectedCategories));
            }

            function loadProducts() {
                var jsonData = JSON.stringify(selectedCategories);

                $.ajax({
                    url: '@Url.Action("GetCategories", "ECommerce")',
                    type: 'POST',
                    data: jsonData,
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        console.log(data);
                        renderProducts(data.ProductData);
                        updatePagination(data.MetaData.page, data.MetaData.pages);
                    },
                    error: function (error) {
                        console.error('Error Occurred:', error);
                    }
                });
            }

            function renderProducts(products) {
                $('#productContainer').empty();
                // ... (same as before)
            }

            function updatePagination(currentPage, totalPages) {
                $('.pagination').empty();
                for (var i = 1; i <= totalPages; i++) {
                    var isActive = i === currentPage ? "active" : "";
                    var pageItem = `<li class="page-item ${isActive}">
                                        <a class="page-link" href="#">${i}</a>
                                    </li>`;
                    $('.pagination').append(pageItem);
                }
            }
        });
    </script>
}

评论

0赞 Onur Serbes 10/27/2023
它有点工作,但不是完全工作。如果我使用分页移动到另一个页面,它不会放置该页面的数据。初始数据会不断显示在其他页面上。始终显示每个页面的前六个数据。我看不到其余的数据。在本地存储之前,它可以正常工作。它会弹出没有过滤的其余数据,然后再次显示过滤后的前六个数据。我无法解决问题
0赞 Onur Serbes 10/30/2023
你有时间检查问题 Jalpa 吗,我根据我提到的问题更新了帖子?
0赞 Jalpa Panchal 10/31/2023
@OnurSerbes我已经根据您的描述更新了我的邮政编码,但存在分页问题。如果它仍然不起作用,请告诉我
0赞 Onur Serbes 10/31/2023
谢谢 Jalpa,我根据您的回答更新了代码并进行了更多修改。现在它正在工作,我分享了该帖子的完整答案。
1赞 Onur Serbes 10/31/2023 #2

根据 Jalpa Panchal 的回答,我进一步修改了脚本,使代码正常工作。我修复了分页和分类问题。以下是代码的更新和最终版本

控制器

    [Authorize]
    [HttpPost]
    public async Task<IActionResult> GetCategories([FromBody] GetECommerceIndexQuery request)
    {
        var result = await MediatrSend(request);
        return Json(result);
    }

脚本

@section scripts {
    <script>
        $(document).ready(function () {
            var selectedCategories = JSON.parse(localStorage.getItem('selectedCategories')) || [];
            var currentPage = parseInt(localStorage.getItem('currentPage')) || 1;

            // Function to update selected categories
            function updateSelectedCategories() {
                selectedCategories = $(".checkbox-item:checked").map(function () {
                    return parseInt(this.value, 10);
                }).get();
                localStorage.setItem('selectedCategories', JSON.stringify(selectedCategories));
            }

            // Function to load products and update pagination
            function loadProducts() {
                var jsonData = JSON.stringify({
                    CategoryIds: selectedCategories,
                    Page: currentPage
                });

                $.ajax({
                    url: '@Url.Action("GetCategories", "ECommerce")',
                    type: 'POST',
                    data: jsonData,
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        console.log(data);
                        renderProducts(data.ProductData);
                        updatePagination(currentPage, data.MetaData.pages);
                    },
                    error: function (error) {
                        console.error('Error Occurred:', error);
                    }
                });
            }

            // Function to render products
            function renderProducts(products) {
                $('#productContainer').empty();

                $.each(products, function (index, product) {
                    var productUrl = '@Url.Action("ProductDetail", new { id = 0 })'.replace("0", product.Id);

                    var productHtml = `
                                                <div class="col-md-4 col-lg-12 col-xxl-4">
                                                    <a href="${productUrl}" class="product-link">
                                                        <div class="card card-custom gutter-b card-stretch">
                                                            <div class="card-body d-flex flex-column rounded bg-light justify-content-between">
                                                                <div class="text-center rounded mb-7">
                                                                    <img src="assets/media/products/${product.ProductName}" class="mw-100 w-200px" alt="${product.ProductName}">
                                                                </div>
                                                                <div>
                                                                    <h4 class="font-size-h5">
                                                                        <span class="text-dark-75 font-weight-bolder">${product.ProductName}</span>
                                                                    </h4>
                                                                    <div class="font-size-h6 text-muted font-weight-bolder">${product.Price}</div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </a>
                                                </div>`;

                    $('#productContainer').append(productHtml);
                });
            }

            // Function to update pagination
            function updatePagination(currentPage, totalPages) {
                $('.pagination').empty();
                for (var i = 1; i <= totalPages; i++) {
                    var isActive = i === currentPage ? "active" : "";
                    var pageItem = `<li class="page-item ${isActive}">
                                                <a class="page-link" href="#" data-page="${i}">${i}</a>
                                            </li>`;
                    $('.pagination').append(pageItem);
                }
            }

            // Initial load of products and pagination
            loadProducts(currentPage);

            // Click event for category checkboxes
            $(".checkbox-item").click(function () {
                updateSelectedCategories();
                currentPage = 1;
                localStorage.setItem('currentPage', currentPage);
                loadProducts();
            });

            // Click event for pagination buttons
            $(".pagination").on("click", ".page-link", function (e) {
                e.preventDefault();
                var page = parseInt($(this).data("page"));
                currentPage = page;
                localStorage.setItem('currentPage', currentPage);
                loadProducts();
            });
        });
    </script>
}