如何在Kendo网格的模型设置中(在javascript中)将列/字段绑定到json结果的子属性?例如,我希望网格包含列:FName,LName,Street和Address。基本上我想要展平Web服务返回的层次结构。
剑道设置
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"
}
}
答案 0 :(得分:3)
你不是那样做的。您需要创建一个类“模型”来展平数据图。您可以在构建模型期间使用延迟加载。通过控制器将此模型发送到View,或将其附加到发送到View的更大的ViewModel(只是模型模型而不是MVVM)。然后将其绑定到Grid。
但是,您会更乐意使用与JSON相同的模型的Ajax加载,这是我认为您正在尝试做的。
模型
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();
}
}
控制器
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);
}
但我不认为Will会成为费城的。 ;)