这让我发疯了...我在这里检查了很多与我的问题相关的帖子,但仍无法解决我的问题。 简而言之: 我使用'$ .Ajax.BeginForm'来更新我的模型observableArray。数据在那里,表被更新,但是,当我检查该数组的长度时,它保持为0!我在这里想念的是什么?
这是数据:
视图模型:
<script type="text/javascript">
//VIEW MODEL DECLARATION:
var ViewModel = {
SubscriberEmail: ko.observable(""),
SubscriberLists: ko.observableArray([]),
UnsubscribeAll: ko.observable(false),
UpdateSubscriberLists: function ()
{
$.ajax("/Home/UpdateSubscriptionInfo/", {
data: ko.toJSON({ lists: this.SubscriberLists }),
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
$().toastmessage('showNoticeToast', data);
}
});
},
ProcessUnsubscribeAll: function() {
if (this.UnsubscribeAll)
{
alert('changing');
alert(ViewModel.SubscriberLists().length);
ko.utils.arrayForEach(ViewModel.SubscriberLists(), function (item)
{
alert("changing OptIn");
//item.OptIn = false;
});
};
}
};
//UTILITY FUNCTIONS:
function DisplayMessage(data)
{
$().toastmessage('showNoticeToast', data);
}
function ProcessListsReceived(data)
{
ViewModel.SubscriberLists(ko.mapping.fromJSON(data));
}
//ON DOCUMENT LOADED:
$(document).ready(function ()
{
ko.applyBindings(ViewModel);
});
</script>
要求更新的部分:
<div class="navbar-right form-inline" style="margin-top: 10px;">
@using (Ajax.BeginForm("GetSubscriptionInfo",
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "ProcessListsReceived"
}))
{
<div class="form-group">
<span class="glyphicon glyphicon-search"> </span>
<label class="sr-only" for="inputemail">Email address</label>
<input data-bind="text:SubscriberEmail" type="email" class="form-control input-sm" id="inputemail" name="inputemail" placeholder="Enter your email" style="width: 300px;">
</div>
<button type="submit" class="btn btn-default input-sm btn-primary" data-loading-text="Loading...">Get my subscriptions</button>
}
</div>
在Javascript部分更新上面声明的可观察数组的函数 -
function ProcessListsReceived(data)
{
ViewModel.SubscriberLists(ko.mapping.fromJSON(data));
}
我有一个绑定到数组长度的按钮..它总是保持禁用状态:
<button data-bind="click: UpdateSubscriberLists, enable: SubscriberLists().length > 0" type="button" class="btn btn-warning">Update subscription</button>
SO ....为什么更新后数组长度为0?谢谢你的任何提示!!
AL
答案 0 :(得分:0)
好的,似乎'ko.mapping.fromJSON'在我的情况下不会更新我的数组的长度... 重写代码进行实际推送就可以了,我的数组正确反映了元素的数量。
所以而不是:
function ProcessListsReceived(data)
{
ViewModel.SubscriberLists(ko.mapping.fromJSON(data));
}
我已声明:
var SubscriberList = function (id,name,desc,optin) {
this.ListID = ko.observable(id);
this.ListName = ko.observable(name);
this.ListDescription = ko.observable(desc);
this.OptIn = ko.observable(optin);
};
并将该函数重写为:
function ProcessListsReceived(data) {
$(jQuery.parseJSON(data)).each(function ()
{
ViewModel.SubscriberLists.push(new SubscriberList(this.ListID, this.ListName, this.ListDescription, this.OptIn));
});
}
现在可以了。谢谢, 人