如何在WebGrid中基于非空参数条件添加含锚点和图片的列?
在WebGrid中实现带图片的条件链接列
我来帮你一步步解决这两个问题,WebGrid的自定义列和条件显示其实有挺灵活的实现方式,下面分情况说明:
1. 实现包含img标签的a标签列
在WebGrid的列定义中,你可以通过format委托来生成自定义的HTML内容。假设你要生成的链接是用来下载或预览Boleto这个byte[]内容,通常这类场景会指向一个处理程序(比如MVC Action)来返回文件流。
举个ASP.NET MVC中的示例代码:
@{ var grid = new WebGrid(Model); } @grid.GetHtml( columns: grid.Columns( // 其他固定列... grid.Column( columnName: "DownloadBoleto", header: "Boleto", format: @<text> <a href="@Url.Action("DownloadBoleto", "Home", new { fileName = item.Nome_Arquivo })" target="_blank"> <img src="@Url.Content("~/Images/download-icon.png")" alt="下载Boleto" title="点击下载Boleto" /> </a> </text> ) ) )
对应的后端Action示例(用来返回文件流):
public ActionResult DownloadBoleto(string fileName) { // 从数据源获取对应的Boleto数据 var boletoData = GetBoletoByFileName(fileName); if (boletoData != null && boletoData.Boleto != null && !string.IsNullOrEmpty(boletoData.Nome_Arquivo)) { // 根据实际文件类型调整MIME类型,这里假设是PDF return File(boletoData.Boleto, "application/pdf", boletoData.Nome_Arquivo); } return HttpNotFound(); }
2. 条件判断的位置与方式
根据你的需求,我提供两种常用的判断方案,你可以根据场景选择:
方式一:控制每行的单元格内容显示
如果希望列始终保留(显示表头),但只有当当前行的item.Boleto和item.Nome_Arquivo都不为空时,才显示带图片的链接,否则单元格为空。直接在format委托里加入条件判断即可:
grid.Column( columnName: "DownloadBoleto", header: "Boleto", format: @<text> @if (item.Boleto != null && !string.IsNullOrEmpty(item.Nome_Arquivo)) { <a href="@Url.Action("DownloadBoleto", "Home", new { fileName = item.Nome_Arquivo })" target="_blank"> <img src="@Url.Content("~/Images/download-icon.png")" alt="下载Boleto" title="点击下载Boleto" /> </a> } </text> )
这种方式能保持表格布局的一致性,空行的单元格仅无内容,不会破坏整体结构。
方式二:控制整个列是否显示
如果希望只有当数据源中至少有一行满足Boleto和Nome_Arquivo都不为空的条件时,才显示这个列。可以先做全局判断,再动态添加列:
@{ var grid = new WebGrid(Model); // 判断是否存在符合条件的行 bool hasValidBoleto = Model.Any(item => item.Boleto != null && !string.IsNullOrEmpty(item.Nome_Arquivo)); var columns = new List<WebGridColumn>(); // 添加其他固定列 columns.Add(grid.Column("Id", "ID")); columns.Add(grid.Column("Nome", "Nome")); // 仅当有符合条件的行时,添加Boleto列 if (hasValidBoleto) { columns.Add(grid.Column( columnName: "DownloadBoleto", header: "Boleto", format: @<text> @if (item.Boleto != null && !string.IsNullOrEmpty(item.Nome_Arquivo)) { <a href="@Url.Action("DownloadBoleto", "Home", new { fileName = item.Nome_Arquivo })" target="_blank"> <img src="@Url.Content("~/Images/download-icon.png")" alt="下载Boleto" title="点击下载Boleto" /> </a> } </text> )); } } @grid.GetHtml(columns: columns)
这种方式适合所有行都无有效Boleto时,完全隐藏列,避免出现空表头的情况。
额外提示
- 对于
byte[]类型的Boleto,直接用!= null判断是否为空即可(SQL查询无值时已设为null)。 - 对于
string类型的Nome_Arquivo,用!string.IsNullOrEmpty()判断更严谨,能同时覆盖null和空字符串的情况。
内容的提问来源于stack exchange,提问作者lat94
相关产品推荐
相关产品推荐

