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

h9a6wy2h  于 12个月前  发布在  .NET
关注(0)|答案(2)|浏览(85)

我正在尝试创建一个电子商务页面。我想使用复选框进行类别选择。它可以进行过滤并给予必要的数据;后端工作。但是当我更改页面(分页功能)时,类别选择丢失。因此数据不再稳定。列表再次为我提供默认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>
}

kokeuurv

kokeuurv1#

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

@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>
}

字符串

whhtz7ly

whhtz7ly2#

根据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>
}

相关问题