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

已有展示视图模型列表的WebGrid,如何实现点击行跳转视图?

实现WebGrid行点击跳转的两种实用方案

嘿,我来帮你搞定WebGrid行点击跳转的需求!这里有两种接地气的方案,你可以根据自己的场景选:

方法一:给每行绑定JavaScript点击事件

这种方法直接给表格的<tr>标签加onclick事件,用户点整行任意位置都会触发跳转,还能优化鼠标样式提示可点击:

WebGrid grid = new WebGrid(Model.ClientMatches);
@grid.GetHtml(
    columns: new[] { 
        grid.Column("Name"), 
        grid.Column("Surname"), 
        grid.Column("Email") 
    },
    rowAttributes: item => new Dictionary<string, object> {
        // 替换成你的目标控制器、动作方法,以及模型里的唯一标识字段(比如Id)
        { "onclick", $"window.location.href='/YourController/YourAction/{item.Id}'" },
        { "style", "cursor: pointer;" } // 鼠标悬停显示手型,提升用户体验
    }
)

小提示:

  • 如果不需要传递参数,直接写固定跳转地址就行,比如window.location.href='/Home/Details'。
  • rowAttributes会给每一行的<tr>标签添加上指定属性,确保整行都能响应点击。

方法二:把单元格内容转为跳转链接

如果更习惯用ASP.NET自带的ActionLink组件,可以把每个单元格的内容包裹成链接,点击任意单元格都能跳转:

第一步:修改WebGrid代码

WebGrid grid = new WebGrid(Model.ClientMatches);
@grid.GetHtml(
    columns: new[] { 
        grid.Column("Name", format: item => Html.ActionLink(item.Name.ToString(), "YourAction", "YourController", new { id = item.Id }, null)),
        grid.Column("Surname", format: item => Html.ActionLink(item.Surname.ToString(), "YourAction", "YourController", new { id = item.Id }, null)),
        grid.Column("Email", format: item => Html.ActionLink(item.Email.ToString(), "YourAction", "YourController", new { id = item.Id }, null))
    },
    rowAttributes: item => new Dictionary<string, object> {
        { "style", "cursor: pointer;" }
    }
)

第二步:添加CSS优化(可选)

要是想让链接占满整个单元格,实现“点击整行任意位置都跳转”的效果,加一段CSS就行:

tr td a {
    display: block;
    width: 100%;
    height: 100%;
    text-decoration: none;
    color: inherit; /* 保持原文字颜色,避免默认链接样式干扰 */
}

小提示:

  • Html.ActionLink会自动处理路由,比硬写URL更安全可靠,适合ASP.NET项目的规范。
  • 记得把YourController、YourAction和item.Id替换成你项目里的实际内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:22:07