2011-09-01 111 views
1

令人惊讶的是,我一直在互联网上搜索如何绑定最近3小时为数据源的复杂类型的webgrid列。但我找不到任何有用的信息。 Complex WebGrid Binding in MVC 3上有一个主题,但它在我的方案中不起作用。WebGrid中的复杂类型

为了简化它,假设我有一个Employee对象列表,我填充了WebGrid,每个Employee都有Address属性,它是Address类型。

我想显示WebGrid中的地址字段的City属性以及Employee的其他字段。

我认为grid.Column(“Address.City”)可以工作,但它不会。这是不支持的东西,或者我做错了什么。

感谢您的帮助。

问候

AnarchistGeek

回答

0

这是我在ASP.NET论坛得到了答案,我想在这里发布的情况下,其他人可能需要这一点。

线程链接http://forums.asp.net/p/1718114/4586676.aspx/1?Re%20Complex%20data%20type%20in%20WebGrid

和解决方案(测试):

@functions{ 
    public class Employee 
    { 
     public string Name { get; set; } 
     public Address Address { get; set; } 
    } 
    public class Address 
    { 
     public string City { get; set; } 
    } 
} 
@{ 
    var myClasses = new List<Employee>{ 
      new Employee { Name="A" , Address = new Address{ City="AA" }}, 
      new Employee { Name="B" , Address = new Address{ City="BB" }}, 
      new Employee { Name="C" , Address = new Address{ City="CC" }}, 
      new Employee { Name="D" , Address = new Address{ City="DD" }}, 
}; 
    var grid = new WebGrid(source: myClasses); 
} 
@grid.GetHtml(
columns: grid.Columns(grid.Column("Address.City",header:"City"), grid.Column("Name"))) 

我希望它可以帮助别人。

干杯。

1

我看不出你的答案如何解决问题,直到我意识到我所缺少的是有时该属性可以为null,而不是空引用错误,你会得到错误列“Address.City”会不存在。除非您检查格式属性中的空值.... I found the the answer here

@functions{ 
     public class Employee 
     { 
      public string Name { get; set; } 
      public Address Address { get; set; } 
     } 
     public class Address 
     { 
      public string City { get; set; } 
     } 
    } 
    @{ 
     var myClasses = new List<Employee>{ 
       new Employee { Name="A" , Address = new Address{ City="AA" }}, 
       new Employee { Name="B" , Address = new Address{ City="BB" }}, 
       new Employee { Name="C" , Address = new Address{ City=null }}, 
       new Employee { Name="D" , Address = null}, 
    }; 
     var grid = new WebGrid(source: myClasses); 
    } 
    @grid.GetHtml(
    columns: grid.Columns(grid.Column("Address.City", 
    header: "City", 
    format: @<text>@if (item.Address != null) 
        {@item.Address.City} 
    </text>), 
    grid.Column("Name")))