如何实现按价格排序的动态下拉菜单,选择后自动触发排序并刷新页面
实现动态排序下拉菜单的解决方案
1. 修正并优化HTML下拉菜单
你当前的HTML中所有选项value都为1,无法区分不同排序类型,需要给每个选项设置唯一标识,同时添加onchange事件实现无按钮自动跳转:
<div class="sorting"> <select onchange="window.location.href = this.value;"> <option value="@Url.Action("Index", "Product", new { category = Model.categoryType, sort = "default" })">Default sorting</option> <option value="@Url.Action("Index", "Product", new { category = Model.categoryType, sort = "priceAsc" })">Price low to high</option> <option value="@Url.Action("Index", "Product", new { category = Model.categoryType, sort = "priceDesc" })">Price high to low</option> </select> </div>
这里用@Url.Action生成符合路由规则的URL,自动携带当前分类和排序参数,选择选项时直接触发页面跳转。
2. 修改控制器Index方法
给方法添加sort参数,根据参数对产品列表进行排序:
public IActionResult Index(string category, string sort = "default") { IndexVM model = new IndexVM(); // 获取基础产品列表 var products = productRepository.getProducts(category); // 根据排序参数执行对应排序逻辑 switch(sort) { case "priceAsc": products = products.OrderBy(p => p.Price).ToList(); break; case "priceDesc": products = products.OrderByDescending(p => p.Price).ToList(); break; default: // 默认排序规则,示例按产品ID排序,可根据需求调整 products = products.OrderBy(p => p.Id).ToList(); break; } model.products = products; model.categoryType = category; model.allItemsCount = model.products.Count; model.raceChipsCount = productRepository.getCategoryItemsCount("Chip tuning"); model.carInteriorCount = productRepository.getCategoryItemsCount("Car interior"); model.ExhaustSystemsCount = productRepository.getCategoryItemsCount("Exhaust system"); model.gearBoxesCount = productRepository.getCategoryItemsCount("Gear boxes"); model.enginePartsCount = productRepository.getCategoryItemsCount("Engine parts"); return View(model); }
注意:如果
getProducts返回的是IQueryable类型,排序会在数据库层面执行,效率更高;如果是List则在内存中排序。
3. 可选优化:保持选中状态
让页面刷新后下拉菜单自动选中当前排序选项,需要在IndexVM中添加Sort属性:
public class IndexVM { // 原有属性... public string Sort { get; set; } }
然后在控制器中赋值:
model.Sort = sort;
最后修改HTML的option标签,添加选中判断:
<div class="sorting"> <select onchange="window.location.href = this.value;"> <option value="@Url.Action("Index", "Product", new { category = Model.categoryType, sort = "default" })" @(Model.Sort == "default" ? "selected" : "")>Default sorting</option> <option value="@Url.Action("Index", "Product", new { category = Model.categoryType, sort = "priceAsc" })" @(Model.Sort == "priceAsc" ? "selected" : "")>Price low to high</option> <option value="@Url.Action("Index", "Product", new { category = Model.categoryType, sort = "priceDesc" })" @(Model.Sort == "priceDesc" ? "selected" : "")>Price high to low</option> </select> </div>
内容的提问来源于stack exchange,提问作者AzSumToshko
相关产品推荐
相关产品推荐

