How can I hide a WebGrid column based on the current user's role?

狂风中的少年 提交于 2019-12-05 23:59:26

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();
    }
}

and then in your view:

@{
    var grid = new WebGrid(Model);
}
@grid.GetHtml(columns: grid.Columns(Html.RoleBasedColumns(grid)))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!