问题
I am trying to trying to set a the binding a drop down list (kendo drop down) uses to a full object. I am using Knockout-Kendo to accomplish the binding but I don't think the kendo stuff or knockout-kendo stuff is a factor in my problem.
For example I have the following object
var model = {
"Client": null,
"Clients": [
{
"CompanyAccount": {
"RelationshipManager": {},
"CompanyAccountId": 1,
"Name": "My Company Name",
"PhoneNumber": "(555) 555-5555",
"Address": {
"State": {
"StateId": 6,
"Name": "New York",
"Abbreviation": "NY"
},
"AddressId": 1,
"Street1": "123 Any Street",
"Street2": null,
"City": "New York",
"StateId": 6,
"Zip": 12345
}
},
"ClientId": 1,
"Name": "New Client 1/30/2013",
"CompanyAccountId": 1,
"ContactName": null,
"Salutation": null,
"ClientAddress": null,
"OfficePhoneNumber": null,
"OfficePhoneExtension": null,
"MobilePhoneNumber": null,
"Email": null,
"TrackingState": 0
}
]
}
}
I use the knockout-mapping plugin to turn all the stuff into an observable.
var viewModel = ko.mapping.fromJS(model); ko.applyBindings(viewModel);
My html binding looks like this
<select data-bind="kendoDropDownList: { dataTextField: 'Name', optionLabel: 'Select An Client...', dataValueField: 'ClientId', data: Clients, value: Client }"></select>
But I'd like to set the Client
property with data like
Client: {
"CompanyAccount": {
"RelationshipManager": {},
"CompanyAccountId": 1,
"Name": "My Company Name",
"PhoneNumber": "(555) 555-5555",
"Address": {
"State": {
"StateId": 6,
"Name": "New York",
"Abbreviation": "NY"
},
"AddressId": 1,
"Street1": "123 Any Street",
"Street2": null,
"City": "New York",
"StateId": 6,
"Zip": 12345
}
},
"ClientId": 1,
"Name": "New Client 1/30/2013",
"CompanyAccountId": 1,
"ContactName": null,
"Salutation": null,
"ClientAddress": null,
"OfficePhoneNumber": null,
"OfficePhoneExtension": null,
"MobilePhoneNumber": null,
"Email": null,
"TrackingState": 0
}
I can only figure out how to set the property with data like '1' or 'New Client 1/30/2013'
* Edit I am trying to design this because my lack of experience with Entity Framework. If I have a foreign key and an object that is tied to the foreign key in my model that is sent to the client. Updating the foreign key but not the model causes inconsistent state exception on the model when calling SaveChanges(). I think my best approach now is to create a ViewModel without those objects (only containing the ForeignKey Ids).
回答1:
This Kendo UI widget does not support setting the value as an object. You would need to set the value to a unique key (ClientId
) and then use a computed observable to retrieve the actual object.
Something like: http://jsfiddle.net/rniemeyer/xz2uY/
this.selectedId = ko.observable("2");
this.selectedChoice = ko.computed(function() {
var id = this.selectedId();
return ko.utils.arrayFirst(this.choices(), function(choice) {
return choice.id === id;
});
}, this);
来源:https://stackoverflow.com/questions/14613550/set-the-binding-of-a-dropdown-in-knockout-to-an-object