Reputation: 3186
I have, surprisingly, been searching on the internet how to bind a webgrid column from a complex type that is data source last 3 hours. But I could not find any useful information. there is a topic on Complex WebGrid Binding in MVC 3, but it did not work in my scenario.
To simplify it, let's say I have a list of Employee objects that I populate WebGrid from, each Employee have Address property which is Address type.
I would like to show the City property of Address field in the WebGrid along with other fields of Employee.
I assumed that grid.Column("Address.City") would work, but it does not. Is that something not supported, or I am doing something wrong.
Thanks for your help.
Regards
AnarchistGeek
Upvotes: 1
Views: 2577
Reputation: 22595
I could not see how your answer was fixing the issue until I realised that what I was missing is that sometimes the property can be null but instead of a null reference error you get the error Column "Address.City" does not exist. unless you check for null in the format property....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")))
Upvotes: 1
Reputation: 3186
This is the answer I got in ASP.NET forums and I wanted post it here in case others may need that.
The thread link is http://forums.asp.net/p/1718114/4586676.aspx/1?Re%20Complex%20data%20type%20in%20WebGrid
and the solution is(Tested):
@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")))
I hope it helps others.
Cheers.
Upvotes: 0