我正在尝试从ajax调用中加载选择标签。我可以加载select语句,但是当我尝试分配值时会失败。谢谢你的帮助!
HTML代码
<select data-bind="value: state, options: allStates, optionsText: 'name', optionsValue: 'abbreviation', optionsCaption:'Please pick a state...'" class="form-control" id="state" name="state"></select>'
var cSource = function (data) {
var self = this;'
self.state = ko.observable(data.state);
self.allStates = ko.observableArray([]);
// get the list of states from the server
$.getJSON('@Url.Action( "AllStates", "Home" )', function(myData) {
// myDate is a list of states
self.allStates(myData);
});
Not Assigned
var modelData = @Html.Raw( Json.Encode( Model ) ); // does not contain a list of states
mySource = new cSource(modelData);
ko.applyBindings(mySource);
C#对象
public static List<cStates> usStates()
{
List<cStates> myStates = new List<cStates>();
myStates.Add( new cStates() { abbreviation = "AL", name = "ALABAMA" } );
myStates.Add( new cStates() { abbreviation = "AK", name = "ALASKA" } );
....
return myStates;
}
控制者
public ActionResult AllStates()
{
return Json( ChoiceProducts.States.BLL.cStates.usStates(), JsonRequestBehavior.AllowGet);
}
如果我从javascript json对象加载状态,则可以正常工作。
var states = [{"name": "Alabama","abbreviation": "AL"},{"name": "Alaska",
"abbreviation": "AK"},.....
self.state = ko.observable(data.state);
self.allStates = ko.observableArray(states);
Properly Assigned
最佳答案
您需要使用敲除的ko.utils.arrayMap
来获取服务器中的数据。在应用绑定之前,请执行以下操作:
var mappedState = ko.utils.arrayMap(stateObjectFromServer, function(item) {
return new State(item.name, item.abbreviation);
});
这里有一个很好的资源可以帮助您:
http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html