4

如何在剑道网格的模型设置中将列/字段绑定到 json 的子属性(在 javascript 中)?例如,我希望网格包含列: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"
          }
}
4

1 回答 1

3

你不要那样做。您需要创建一个扁平化数据图的“模型”类。您将能够在构建模型期间使用延迟加载。要么通过控制器将此模型发送到视图,要么将其附加到发送到视图的更大的视图模型(只是模型的模型而不是 MVVM)。然后将其绑定到网格。

但是,您会更乐意使用 Ajax 加载与 JSON 相同的模型,这是我认为您正在尝试做的事情。

模型

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

但我认为威尔永远不会去费城。;)

于 2013-02-08T13:58:33.407 回答