我正在try 创建一个Electron 商务页面.我想使用复选框进行类别 Select .它可以进行过滤,并为我提供必要的数据;后端工作.但当我更改页面(分页功能)时,类别 Select 就丢失了.因此,数据不再稳定.该列表再次为我提供了默认的SQL查询.我怎么才能让它稳定下来呢?如何存储我的 Select ?

EDIT (problem occures to this if I use localStorage, based on the answer)个 如果我需要举个例子让你更好地理解.您的数据中有10个项目,每个项目显示6个项目,当您切换到第二页时,您需要查看其余的4个数据.我的问题出现在这里,我看不到剩下的4个数据.我在每个版本中又看到了前6个.我看到剩下的4个数据(一秒钟),然后我立即看到前6个数据.

If more code blocks are needed I can edit the post

Controller

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

Query File

 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

 <!-- 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>

Script

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

推荐答案

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

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

Asp.net相关问答推荐

/应用程序中的服务器错误. ASP.NET

在 appSettings 中存储字符串数组?

ASP.NET IIS - 请求何时排队?

使用 Elmah 处理 Web 服务中的异常

为什么我不能在 ASP.net MVC 中使用服务器控件?

页面在谷歌浏览器中加载两次

LINQ:使用 Lambda 表达式获取 CheckBoxList 的所有选定值

解析器错误:无法创建类型

ASP.NET 中的全局资源与本地资源

如何从 ASP.Net 发布然后重定向到外部 URL?

GMT 和 UTC 一样吗?

如何验证 WebClient 请求?

HttpContext.Current.Request.Url.Host 它返回什么?

ASP.Net 无法创建/卷影复制

为在 ASP.NET Web API 中使用 User.Identity.Name 的方法编写单元测试

在 ASP.NET 标识中添加角色

GZIP 与 DEFLATE 压缩相比有什么优势?

您可以从 web.config 文件中的其他位置提取 log4net AdoNetAppender 的 connectionString 吗?

在没有等待 #2 的情况下调用异步方法

ASP.NET 自定义控件 - 未知的服务器标记