C# MVC:如何仅在Html:Grid中有值时才显示列?

C# MVC:如何仅在Html:Grid中有值时才显示列?,c#,asp.net-mvc,asp.net-mvc-3,C#,Asp.net Mvc,Asp.net Mvc 3,我想知道如果列表中没有返回任何内容,如何控制列在Html.Grid中是否可见。因此,如果在下面的示例Model.Comment中,ExampleList中没有值,则不应呈现该列 @Html.Grid(Model.ExampleList).Columns(c => { c.For(a => string.Format("{0:dd/MM/yyyy}", a.DateRequested)).Named("Date Requested"); c.Fo

我想知道如果列表中没有返回任何内容,如何控制列在Html.Grid中是否可见。因此,如果在下面的示例Model.Comment中,ExampleList中没有值,则不应呈现该列

@Html.Grid(Model.ExampleList).Columns(c =>
    {
        c.For(a => string.Format("{0:dd/MM/yyyy}", a.DateRequested)).Named("Date Requested");
        c.For(a => a.Comment).Named("Comment");
        c.For(a => a.Completed).Named("Completed");
    })

如何实现这一点?

您应该使用视图模型,并且在该视图模型中,您应该具有一个布尔属性,指示某些内容是否应该可见。显然,确定其值的所有逻辑不是视图责任=>而是控制器或模型。例如,您可以使用以下视图模型:

public class MyViewModel
{
    public bool ShouldDisplayCommentsColumn 
    { 
        get 
        {
            return .... // Check the Items and decide whether you 
                        // should be showing the Comments column or not
        }
    }
    public IEnumerable<SomeOtherViewModel> Items { get; set; }
}
if (Model.ShouldDisplayCommentsColumn)
{
    c.For(a => a.Comment).Named("Comment");
}