gpt4 book ai didi

c# - 如何通过 knockout 保存单条记录

转载 作者:行者123 更新时间:2023-11-28 20:54:00 25 4
gpt4 key购买 nike

我有一个使用 knockout 设置的基本表,但我想知道是否有任何方法可以编辑/保存单个记录,而不是每次进行更改时都必须保存整个 View 模型?这是我的代码...

<tbody data-bind="foreach: movies">
<tr>
<td data-bind="text: title"></td>
<td data-bind="text: releaseDate"></td>
<td data-bind="text: genre"></td>
<td data-bind="text: price"></td>
<td><input type="button" value="Edit" id="edit"/></td>
</tr>
<tr class="editable"> <!-- hide this initially, only show when edit button is clicked -->
<td><input id="titleInput" data-bind="value: title" /></td>
<td><input id="releaseDateInput" data-bind="value: releaseDate" /></td>
<td><input id="genreInput" data-bind="value: genre" /></td>
<td><input id="priceInput" data-bind="value: price" /></td>
</tr>
<!-- save button/form or something here containing ONLY this record -->

</tbody>
</table>


<script type="text/javascript">

function Film(data) {
this.title = ko.observable(data.Title);
this.releaseDate = ko.observable(data.ReleaseDate);
this.genre = ko.observable(data.Genre);
this.price = ko.observable(data.Price);
}

function MovieListViewModel() {
var self = this;
self.movies = ko.observableArray([]);
self.title = ko.observable();
self.releaseDate = ko.observable();
self.genre = ko.observable();
self.price = ko.observable();

$.getJSON("/Movies/GetAllMovies", function (allMovies) {
var mappedMovies = $.map(allMovies, function (movie) { return new Film(movie) });
self.movies(mappedMovies);
});
}

ko.applyBindings(new MovieListViewModel());

有什么想法吗?谢谢!

最佳答案

事实上,通过的魔力binding contexts ,这很简单!

  1. 第一步。将以下元素放置在 foreach 模板内的任意位置。

    <button data-bind="click: $root.saveMovie">Save</button>
  2. 第二步。将 saveMovie 方法添加到您的 viewModel

    self.saveMovie = function(movie) {
    $.ajax({
    type: "POST",
    url: "/someurl",
    dataType: "json",
    contentType: "application/json",
    data: ko.toJSON(movie),
    success: function(result) {
    //...
    }
    });
    }

movie 变量将包含 foreach 循环的项目!为什么?因为在 Knockout 中,我们有一个令人惊奇的功能,称为绑定(bind)上下文:

A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko.applyBindings(viewModel). Then, each time you use a control flow binding such as with or foreach, that creates a child binding context that refers to the nested view model data.

http://knockoutjs.com/documentation/binding-context.html

关于c# - 如何通过 knockout 保存单条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11940556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com