3

I need to do a grid using webgrid and I would like to hide the column (header and items) of edit actions based on user role.

How can I do that with webgrid?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Cleyton T.
  • 33
  • 1
  • 3

1 Answers1

2

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)))
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928