且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据当前用户的角色隐藏WebGrid列?

更新时间:2023-11-30 10:27:22

您可以编写一个帮助程序方法,该方法将根据用户角色动态生成列:

You could write a helper method which would generate the columns dynamically based on user roles:

public static class GridExtensions
{
    public static WebGridColumn[] RoleBasedColumns(
        this HtmlHelper htmlHelper, 
        WebGrid grid
    )
    {
        var user = htmlHelper.ViewContext.HttpContext.User;
        var columns = new List<WebGridColumn>();

        // The Prop1 column would be visible to all users
        columns.Add(grid.Column("Prop1"));

        if (user.IsInRole("foo"))
        {
            // The Prop2 column would be visible only to users
            // in the foo role
            columns.Add(grid.Column("Prop2"));
        }
        return columns.ToArray();
    }
}

,然后在您看来:

@{
    var grid = new WebGrid(Model);
}
@grid.GetHtml(columns: grid.Columns(Html.RoleBasedColumns(grid)))