How to hide columns in WebGrid?

I am new to MVC3. I use WebGrid to display some of the columns on the site for the auction I'm working on. This displays a grid showing recent bids. When anyone other than the administrator logs in, they should only see the bid amounts and the date / time. When an administrator logs in, they should see all the columns (name and contact information). I think I will probably have to somehow massage this into the code, but I was wondering if there is a way to deal with it in Razor markup? Here I have it:

@{ var grid = new WebGrid(Model.Bids.OrderByDescending(b => b.BidAmount)); } @grid.GetHtml( tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt", columns: grid.Columns( grid.Column("BidAmount", format: @<text> $@item.BidAmount </text>), grid.Column("BidDateTime"), grid.Column("FirstName"), grid.Column("LastName"), grid.Column("Email"), grid.Column("PhoneNumber") ) ) 

So what I want to do, there is something like this in the pseudo code:

  @{ var grid = new WebGrid(Model.Bids.OrderByDescending(b => b.BidAmount)); } @grid.GetHtml( tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt", columns: grid.Columns( grid.Column("BidAmount", format: @<text> $@item.BidAmount </text>), grid.Column("BidDateTime"), @if(userIsAdmin){ grid.Column("FirstName"), grid.Column("LastName"), grid.Column("Email"), grid.Column("PhoneNumber") ) } ) 

Can this be done? If not, any ideas on how to approach it? Do I need to code two different WebGrid and surround them with if (), maybe?

+6
source share
1 answer

If you first make a list of columns in the first block of code into a variable (cols):

 @{ var grid = ...; IEnumerable<WebGridColumn> cols = grid.Columns(... the common columns ...); if (isAdmin) cols = cols.Concat(grid.Columns(... the admin columns ...); } 

And pass it to the GetHtml () method:

 @grid.GetHtml(... columns: cols); 

I think for the Concat method you need a namespace using System.Linq as usual. Alternatively, you can use List<WebGridColumns> and use AddRange.

This is because GetHtml expects an IEnumerable<WebGridColumn> for the columns parameter. The helper method grid.Columns is nothing more than a method with the params array parameter, so you can simply "enumerate" the columns one by one, but you actually make up the params array this way. However, you can use any valid methods that you can imagine in C # to compile a list of (IEnumerable) columns, and then you can pass it to GetHtml.

+5
source

Source: https://habr.com/ru/post/887951/


All Articles