MVC 3 Webgrid - 你如何隐藏你不想看到的列?

时间:2011-08-24 08:15:49

标签: asp.net-mvc razor show-hide webgrid

我有一个webgrid,我希望只有某些用户可以看到一列。 目前我已将网格编码如下

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

但是肯定有更好的方法而不重复所有代码? 2列输入之间的唯一区别是我想显示特定用户的编辑链接。那么这样做的最佳替代方式是什么?

3 个答案:

答案 0 :(得分:27)

尝试这样(未经测试,目前无法访问VS):

@{
    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()));

答案 1 :(得分:0)

grid.Column("FriendlyId", style:"hidecol",header:"")

不要像这样使用它,你应该像下面那样使用它。我试过了,它会成功。

grid.Column(format: @<input type="hidden" name="FriendlyId" value="@item.FriendlyId" />)

答案 2 :(得分:0)

通过使用“columnNames”参数,不确定是否可以让我更简单。我想显示“CustomerCode”列,所以只需将“CustomerCode”列入其他任何列。

WebGrid obj = new WebGrid(Custs,columnNames: new[] { "CustomerCode"});

取自

http://www.codeproject.com/Articles/843788/WebGrid-in-ASP-NET-MVC-important-tips#Tip3:-DisplayNecessaryColumnsMVCWebGrid