2011-06-05 75 views
1

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

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

这怎么能实现?

回答

2

你应该使用一个视图模型,并且在这个视图模型中你应该有一个布尔属性来指示是否应该可见或不可见。显然,确定其价值的所有逻辑不是视图责任=>它是控制器或模型。因此,例如,你可以有以下视图模型:

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