我看不出你的答案如何解決問題,直到我意識到我所缺少的是有時該屬性可以爲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")))