You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC按国家分类供应商:请求协助添加对应供应商数量显示功能

解决方案:显示按国家分组的供应商数量

1. 修改控制器代码

替换原有的ViewBag.supCountries赋值逻辑,通过分组统计直接获取每个国家对应的供应商数量,避免多次查询数据库:

public ActionResult SupplierList(int supID = 0, string country="")
{
    // 按国家分组并统计供应商数量,传递给视图
    ViewBag.CountrySupplierCounts = _db.Suppliers
        .GroupBy(s => s.Country)
        .Select(g => new { Country = g.Key, Count = g.Count() })
        .ToList();

    List<Suppliers> supplierList;

    if (country== "" && supID == 0)
    {
        supplierList = _db.Suppliers.ToList();
    }
    else if (country!= "" && supID == 0)
    {
        supplierList = _db.Suppliers.Where(a => a.Country == country).ToList();
    }
    else
    {
        supplierList= _db.Suppliers.Where(a => a.SupplierID == supID).ToList();
    }

    return View(supplierList);
}

2. 修改视图代码

遍历新传递的分组统计数据,将占位符00替换为对应国家的供应商数量:

<div class="col-md-2">
<ul class="list-group">
    @foreach (var item in ViewBag.CountrySupplierCounts)
    {
        <li class="list-group-item">
            @Html.ActionLink(item.Country, "SupplierList", new { country= item.Country })
            <span style="float:right; color:lightgrey">
                @item.Count
            </span>
        </li>
    }
</ul>
<div>
    @Html.ActionLink("New Supplier", "Create", null, new { @class = "btn btn-success" })
</div>
</div>

说明

  • 控制器中通过GroupBy+Count()的方式,一次性完成国家分组和数量统计,比先取国家列表再逐个查询数量的方式性能更优。
  • 视图中直接访问分组对象的Count属性,即可动态显示对应国家的供应商数量,实现目标效果。

内容的提问来源于stack exchange,提问作者Barış Güneş

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:21:36