Search code examples
asp.net-mvc-3razorwebgrid

Complex type in WebGrid


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


Solution

  • 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.