Kendo UI Grid - How to Bind to Child Properties

懵懂的女人 提交于 2019-12-01 20:46:30

问题


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:


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. ;)



来源:https://stackoverflow.com/questions/14756973/kendo-ui-grid-how-to-bind-to-child-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!