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

Blazor Server端Radzen DataGrid如何选择Property参考值展示关联表字段

实现方法

你需要在列模板中通过当前行的GatewayModel.IdSite匹配站点列表的对应项,取出Name字段显示即可,有两种实现方案可选:


方案1:直接遍历匹配(适合小数据量场景)

修改列模板代码如下:

<RadzenDataGridColumn TItem="GatewayModel" 
       Property="IdSite" Title="Site Name" TextAlign="TextAlign.Right" >
    <Template Context="gatewayItem">
        @(sites.FirstOrDefault(s => s.Id == gatewayItem.IdSite)?.Name ?? "未匹配到站点")
    </Template>
</RadzenDataGridColumn>

说明:

  • Context对应的是当前行的GatewayModel实例,重命名为gatewayItem避免和全局站点列表变量sites重名冲突
  • ?. 为安全访问符,避免匹配不到站点时触发空引用异常
  • ?? 后为兜底显示文本,站点匹配失败时展示

使用前请确保在_Imports.razor中引入Linq命名空间:

@using System.Linq

注意:请将上述代码中的s.Id替换为你SiteModel中实际的主键字段名。


方案2:字典预映射(适合大数据量场景,性能更优)

如果站点和网关数据量较大,逐行遍历站点列表效率低,可以提前构建主键到站点名称的映射字典:

  1. 先在@code代码块中新增字典字段:
// 假设IdSite为int类型,若为Guid则将字典key类型改为Guid
Dictionary<int, string> _siteNameMap;
  1. 在OnInitializedAsync加载完站点数据后初始化字典:
protected override async Task OnInitializedAsync()
{
    string gatesql = "SELECT * FROM gatewaymodel;";
    gateways = await _data.LoadData<GatewayModel, dynamic>(gatesql, new { }, _config.GetConnectionString("MainDB"));

    string sitesql = "SELECT * FROM sitemodel;";
    sites = await _data.LoadData<SiteModel, dynamic>(sitesql, new { }, _config.GetConnectionString("MainDB"));

    // 新增字典初始化代码
    _siteNameMap = sites.ToDictionary(s => s.Id, s => s.Name);
}
  1. 修改列模板直接从字典取值:
<RadzenDataGridColumn TItem="GatewayModel" 
       Property="IdSite" Title="Site Name" TextAlign="TextAlign.Right" >
    <Template Context="gatewayItem">
        @(_siteNameMap.TryGetValue(gatewayItem.IdSite, out var siteName) ? siteName : "未匹配到站点")
    </Template>
</RadzenDataGridColumn>

内容的提问来源于stack exchange,提问作者Tom Boudniatski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:15:03