I am new to MVC3 - I am using a WebGrid to display some columns on a site for an auction I'm working on. This displays a grid showing the latest bids. When anyone except an admin logs in, they should only see the bid amounts and date/time. When an admin logs in, they should see all the columns (name and contact info). I'm thinking I will probably have to massage this in code behind somehow, but I was wondering if there is a way to handle it in Razor markup? Here is the I have now:
@{ 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, in pseudo code, is something like this:
@{ 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? Would I need to code two different WebGrid's, and surround them with an if() maybe?
If would first compose the list of columns in the first code block 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 for System.Linq as usual. Alternatively you can use a List<WebGridColumns>
and use AddRange.
The point is that the GetHtml expects an IEnumerable<WebGridColumn>
for the columns parameter. The grid.Columns helper method is nothing more than a method with a params array parameter so that you can just "list" the columns one after the other, but you actually compose a params array this way. However, you can use any valid methods you can imagine in C# to compose a list (IEnumerable) of columns and you can pass it to the GetHtml afterwards.
精彩评论