Complex WebGrid Binding in MVC 3

2019-07-29 16:04发布

问题:

Let's say I have a Parent object like this (in pseudo code)

public Parent()
  string FirstName
  string LastName
  IEnumarable<Child> Children
  Child GetOldestChild()  <- A function that returns the oldest child in Children

public Child()
  string ChildFirstName
  string ChildLastName
  int ChildAge

Ok, so I want to bind a WebGrid an IEnumarable< Parent >, and in each row I want to display the first and last name of the parent, and the firstname/lastname/age of the oldest child.

Getting the parent columns is easy, I can just bind like this:

grid.Column("FirstName")

But getting the oldest child data is what I don't know how to do. This doesn't work, but it's what I want to accomplish:

grid.Column("GetOldestChild().ChildFirstName")

Hopefully I'm missing something simple...

回答1:

Try this way:

public Parent()
  string FirstName
  string LastName
  IEnumarable<Child> Children
  private Child GetOldestChild()
  public Child OldestChild { get { return GetOldestChild() } };

public Child()
  string ChildFirstName
  string ChildLastName
  int ChildAge

grid.Column("OldestChild.ChildFirstName")


回答2:

Here is a solution I came up with that will allow you to accomplish what you need without creating extraneous properties on your model and will also allow you get parametized data:

Binding MVC WebGrid column to source's dictionary property value