WebGrid Helper and Complex Types
- by imran_ku07
Introduction:
WebGrid helper makes it very easy to show tabular data. It was originally designed for ASP.NET Web Pages(WebMatrix) to display, edit, page and sort tabular data but you can also use this helper in ASP.NET Web Forms and ASP.NET MVC. When using this helper, sometimes you may run into a problem if you use complex types in this helper. In this article, I will show you how you can use complex types in WebGrid helper.
Description:
Let's say you need to show the employee data and you have the following classes,
public class Employee
{
public string Name { get; set; }
public Address Address { get; set; }
public List<string> ContactNumbers { get; set; }
}
public class Address
{
public string City { get; set; }
}
The Employee class contain a Name, an Address and list of ContactNumbers. You may think that you can easily show City in WebGrid using Address.City, but no. The WebGrid helper will throw an exception at runtime if any Address property is null in the Employee list. Also, you cannot directly show ContactNumbers property. The easiest way to show these properties is to add some additional properties,
public Address NotNullableAddress
{
get
{
return Address ?? new Address();
}
}
public string Contacts
{
get
{
return string.Join("; ",ContactNumbers);
}
}
Now you can easily use these properties in WebGrid. Here is the complete code of this example,
@functions{
public class Employee
{
public Employee(){
ContactNumbers = new List<string>();
}
public string Name { get; set; }
public Address Address { get; set; }
public List<string> ContactNumbers { get; set; }
public Address NotNullableAddress
{
get
{
return Address ?? new Address();
}
}
public string Contacts
{
get
{
return string.Join("; ",ContactNumbers);
}
}
}
public class Address
{
public string City { get; set; }
}
}
@{
var myClasses = new List<Employee>{
new Employee { Name="A" ,
Address = new Address{ City="AA" },
ContactNumbers = new List<string>{"021-216452","9231425651"}},
new Employee { Name="C" ,
Address = new Address{ City="CC" }},
new Employee { Name="D" ,
ContactNumbers = new List<string>{"045-14512125","21531212121"}}
};
var grid = new WebGrid(source: myClasses);
}
@grid.GetHtml(columns: grid.Columns(
grid.Column("NotNullableAddress.City", header: "City"),
grid.Column("Name"),
grid.Column("Contacts")))
Summary:
You can use WebGrid helper to show tabular data in ASP.NET MVC, ASP.NET Web Forms and ASP.NET Web Pages. Using this helper, you can also show complex types in the grid. In this article, I showed you how you use complex types with WebGrid helper. Hopefully you will enjoy this article too.