【问题标题】:MVC3 Web Grid adding action links at the begining of columns listMVC3 Web Grid 在列列表的开头添加操作链接
【发布时间】:2026-02-12 21:50:01
【问题描述】:

我正在使用 MVC3 WebGrid 控件来呈现实体列表。假设我有一个类似索引的页面,它呈现用户列表、项目、订单等。所有这些实体都有一个名为 ID 的列。

WebGrid 看起来不错,我唯一想要的是,一旦呈现列表,我想在所有其他列之前添加 3 个操作链接 Edit、Delete、Detail。

添加以下代码有效,但我不想在所有页面中重复此代码:

@grid.GetHtml(columns: grid.Columns(
                grid.Column(header: "",
                   style: "text-align-center",
                       format: (item) => new
                        HtmlString(Html.ActionLink("Edit", "Edit", new { ID = item.ID     }).ToString() + " | " +
                                    Html.ActionLink("Details", "Details", new { ID = item.ID }).ToString() + " | " +
                                    Html.ActionLink("Delete", "Delete", new { ID = item.ID }).ToString()
                                   )
            ),
            grid.Column("FirstName"),
            grid.Column("LastName"),
            grid.Column("EmailAddress")
        )

基本上我想说的是@Grid.Render(Model) ...它应该创建前3个动作链接,它们会渲染模型的所有列。

我知道有 JQuery 网格和 MVCContrib 等,但请不要选择它们。

任何 cmets 和提示将不胜感激。

【问题讨论】:

    标签: asp.net-mvc-3 webgrid


    【解决方案1】:

    您可以为网格编写自定义扩展方法:

    using System.Linq;
    using System.Web;
    using System.Web.Helpers;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    
    public static class WebGridExtensions
    {
        public static IHtmlString MyGetHtml(this WebGrid grid, HtmlHelper html)
        {
            var columns =
                (from n in grid.ColumnNames
                 select new WebGridColumn { ColumnName = n, CanSort = true }
                 ).ToList<WebGridColumn>();
            columns.Insert(0, grid.Links(html));
            return grid.GetHtml(columns: columns, exclusions: new[] { "ID" });
        }
    
        public static WebGridColumn Links(this WebGrid grid, HtmlHelper html)
        {
            return grid.Column(
                header: "",
                style: "text-align-center",
                format: item => new HtmlString(
                    html.ActionLink("Edit", "Edit", new { ID = item.ID }).ToString() + " | " +
                    html.ActionLink("Details", "Details", new { ID = item.ID }).ToString() + " | " +
                    html.ActionLink("Delete", "Delete", new { ID = item.ID }).ToString()
                )
            );
        }
    }
    

    然后使用它:

    @model IEnumerable<MyViewModel>
    @{
        var grid = new WebGrid(Model);
    }
    @grid.MyGetHtml(Html)
    

    或者如果你想控制其他列的构建:

    @grid.GetHtml(
        columns: grid.Columns(
            grid.Links(Html),
            grid.Column("FirstName"),
            grid.Column("LastName"),
            grid.Column("EmailAddress")
        )
    )
    

    【讨论】:

    • 非常感谢。这就是我需要的!