我在将从服务器收到的 Json 对象映射到预定义的 Javascript 对象时遇到问题,该对象包含绑定中使用的所有必要函数
Javascript代码如下
function Person(FirstName, LastName, Friends) {
var self = this;
self.FirstName = ko.observable(FirstName);
self.LastName = ko.observable(LastName);
self.FullName = ko.computed(function () {
return self.FirstName() + ' ' + self.LastName();
})
self.Friends = ko.observableArray(Friends);
self.AddFriend = function () {
self.Friends.push(new Person('new', 'friend'));
};
self.DeleteFriend = function (friend) {
self.Friends.remove(friend);
};
}
var viewModel = new Person();
$(document).ready(function () {
$.ajax({
url: 'Home/GetPerson',
dataType: 'json',
type: 'GET',
success: function (jsonResult) {
viewModel = ko.mapping.fromJS(jsonResult);
ko.applyBindings(viewModel);
}
});
});
HTML:
<p>First name: <input data-bind="value: FirstName" /></p>
<p>Last name: <input data-bind="value: LastName" /></p>
<p>Full name: <span data-bind="text: FullName" /></p>
<p>#Friends: <span data-bind="text: Friends().length" /></p>
@*Allow maximum of 5 friends*@
<p><button data-bind="click: AddFriend, text:'add new friend', enable:Friends().length < 5" /></p>
<br>
@*define how friends should be rendered*@
<table data-bind="foreach: Friends">
<tr>
<td>First name: <input data-bind="value: FirstName" /></td>
<td>Last name: <input data-bind="value: LastName" /></td>
<td>Full name: <span data-bind="text: FullName" /></td>
<td><button data-bind="click: function(){ $parent.DeleteFriend($data) }, text:'delete'"/></td>
</tr>
</table>
我用于获取初始数据的 ServerSide MVC 代码如下所示:
public ActionResult GetPerson()
{
Person person = new Person{FirstName = "My", LastName="Name",
Friends = new List<Person>
{
new Person{FirstName = "Friend", LastName="Number1"},
new Person{FirstName = "Friend", LastName="Number2"}
}
};
return Json(person, JsonRequestBehavior.AllowGet);
}
我正在尝试使用映射插件将 Json 加载到我的 Javascript 对象中,以便所有内容都可用于绑定(添加函数和 Friend 对象上的计算属性)。
当我使用映射插件时,它似乎不起作用。使用插件时,AddFriend 方法在绑定期间不可用。是否可以使用映射插件填充 JavaScript Person 对象,还是必须手动完成所有操作?