4
votes

How to bind a column/field to a child property of the json result in the model settings of the Kendo grid (in javascript)? For example, I want the grid to contain columns: FName, LName, Street and Address. Basically I want to flatten the hierarchical structure returned by the web service.

Kendo Settings

fields: {
    FName: { type: "string" },
    LName: { type: "string"  },
    // How to map to child properties below?
    Street: { field: "Address.Street" },    // this is wrong             
    City: { field: "Address.City" }         // this is wrong
}

JSON

{
   "FName": "William",
   "LName ": "Shakespeare",            
   "Address":
          {
          "Address": "123 Street Ln",
          "City": "Philadelphia"
          }
}
1

1 Answers

3
votes

You don't do it like that. You need to create a class 'Model' that flattens the data graph. You will be able to use lazy loading during the construction of the Model. Either send this Model to the View via the controller or attach it to a larger ViewModel (just a Model of Models not MVVM) that is sent to the View. Then bind this to the Grid.

But, you will be happier to use Ajax loading of the same Model as JSON, which is what I think you are trying to do.

Model

public class ContactModel
{
    public string FName { get; set; }
    public string LName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }

    public ContactModel()
    {}
    public ContactModel(Contact contact) // IContact is better if you have Interfaces
    {
        FName = contact.FName;
        LName = contact.LName;
        Address = contact.Address.Address;
        City = contact.Address.City;
    }

    // Neat Linq trick to convert database query results directly to Model
    public static IList<ContactModel> FlattenToThis(IList<Contact> contacts)
    {
        return contacts.Select(contact => new ContactModel(contact)).ToList();
    }
}

Controller

public JsonResult ReadContacts([DataSourceRequest]DataSourceRequest request)
{
    var contacts = _contactsDataProvider.Read(); // Your database call, etc.
    DataSourceResult result = ContactModel.FlattenToThis(contacts).ToDataSourceResult(request);
    return Json(result, JsonRequestBehavior.AllowGet);
}

But I don't think Will ever made it to Philly. ;)