[英]Knockout MVC, bind model & add object to model
How can I add an item to a List<ComplexObject>
with KnockoutJS
? 如何使用KnockoutJS
将项目添加到List<ComplexObject>
?
This is my model: 这是我的模型:
public class MyModel
{
public List<User> Users { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
This is the client side script: 这是客户端脚本:
<script type="text/javascript">
var viewModel = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)));
ko.applyBindings(viewModel);
// attempt:
var newUser = [{ "Id": "13", "Name": "John" }];
</script>
How do I add newUser
to the the viewModel
? 如何将newUser
添加到viewModel
?
I would do it in the following manner. 我将以以下方式进行操作。
Please see full code below with comments 请查看下面的完整代码并附上注释
// 1. Create a User object
var User = function (Id, Name) {
self = this;
self.Id = Id;
self.Name = Name;
}
// 2. Create a mapping
var mapping = {
'Users': {
create: function(options) {
return new User(options.data.Id, options.data.Name);
}
}
}
var data = @Html.Raw(Json.Encode(Model));
var viewModel = ko.mapping.fromJS(data, mapping);
// output to verify binding
console.log(viewModel);
// 3. Add the new User object
viewModel.Users.push(new User(2, "Jim"));
// output to verify added user
console.log(viewModel.Users());
Update: 更新:
Here is a jsfiddle with it working against a list: 这是一个与列表相对应的jsfiddle:
http://jsfiddle.net/6qsjz/12/ http://jsfiddle.net/6qsjz/12/
Update 2 更新2
The null issue seems to be that you are not initialising the collection, add a constructor to your model like this: 空问题似乎是您没有初始化集合,而是向模型中添加了一个构造函数,如下所示:
public MyModel()
{
Users = new List<User>();
}
See this fiddle... 看到这个小提琴...
http://jsfiddle.net/6qsjz/4/ http://jsfiddle.net/6qsjz/4/
It's a little more like you've got. 有点像您拥有的。 The view model element, along with your rawData should be defined before your bindings are applied. 在应用绑定之前,应先定义视图模型元素以及rawData。
var rawData = { "OtherStuff": { }, "User": {"id": "1", "name": "Bob"} }
....
viewModel = new ViewModel(rawData);
ko.applyBindings(viewModel, document.getElementById('domElementToBind'));
I then showed 2 different examples of creating your objects. 然后,我展示了创建对象的两个不同示例。 Check out the fiddle and follow up with any further questions. 查看小提琴,并提出任何其他问题。
-----EDITED----- Here's the update so you can add more users. -----编辑-----这是更新,因此您可以添加更多用户。 The key was just to make the User --> Users as an observable array and start pushing new users to it. 关键只是使用户->用户成为可观察的数组,并开始将新用户推向该数组。
http://jsfiddle.net/6qsjz/13/ http://jsfiddle.net/6qsjz/13/
self.newUser = new User();
self.addUser = function() {
self.Users.push(self.newUser);
}
-----EDITED----- Oops. -----编辑-----糟糕。 That's what I get for not looking both ways. 这就是我没有同时寻找两种方式的结果。
http://jsfiddle.net/6qsjz/17/ http://jsfiddle.net/6qsjz/17/
self.addUser = function() {
self.Users.push(new User(self.newUser.id(), self.newUser.name()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.