Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC 3 Webgrid - how do you hide columns you do not want to be visible?

I have a webgrid and there is a column I want to be visible only to certain users. Currently I have coded the grid as follows

if (Context.User.IsInRole(Role.Inputter) || Context.User.IsInRole(Role.Administrator))
{
    @grid.GetHtml(columns: grid.Columns(
        grid.Column(format: (item) => Html.ActionLink("Select", "Details", new { contractId = item.ContractId })),
        grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { contractId = item.ContractId })),
        grid.Column("SignOffDate", "Sign Off Date",
            format: @<text> <span>@item.SignOffDate.ToString("d/M/yyyy")</span></text>),
        grid.Column("FullContractNumber", "Contract Number"),
        grid.Column("ContractTitle", "Title")
    ));
}
else
{ 
    @grid.GetHtml(columns: grid.Columns(
        grid.Column(format: (item) => Html.ActionLink("Select", "Details", new { contractId = item.ContractId })),
        grid.Column("SignOffDate", "Sign Off Date",
            format: @<text> <span>@item.SignOffDate.ToString("d/M/yyyy")</span></text>),
        grid.Column("FullContractNumber", "Contract Number"),
        grid.Column("ContractTitle", "Title")
    ));
}

But surely there is a better way without repeating all that code? The only difference between the 2 column inputs is that I want to display the Edit link for particlaur users. So what is the best alternative way of doing that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try like this (untested, don't have access to VS at the moment):

@{
    var gridColumns = new List<WebGridColumn>();
    gridColumns.Add(grid.Column(format: (item) => Html.ActionLink("Select", "Details", new { contractId = item.ContractId })));
    if (Context.User.IsInRole(Role.Inputter) || Context.User.IsInRole(Role.Administrator))
    {
        gridColumns.Add(grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { contractId = item.ContractId })));
    }
    gridColumns.Add(grid.Column("SignOffDate", "Sign Off Date", format: @<text> <span>@item.SignOffDate.ToString("d/M/yyyy")</span></text>));
    gridColumns.Add(grid.Column("FullContractNumber", "Contract Number"));
    gridColumns.Add(grid.Column("ContractTitle", "Title"));
}

@grid.GetHtml(columns: grid.Columns(gridColumns.ToArray()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...