Knockout复选框绑定,具有自动更新

时间:2014-01-24 03:00:49

标签: asp.net-mvc knockout.js asp.net-web-api

我正在尝试当一个人更改先前绑定的复选框的状态时,我想用新值更新服务器。 所以这就是我所拥有的:

JSCRIPT

function JobViewModel() {
        var self = this;
        var baseUri = '/Api/Pedidos/';

        self.TotalItems = ko.observable(@Model.TotalItems);
        self.AbreviaNome = ko.observable(@Model.AbreviaNome.ToString().ToLower());
        self.AbreviaFantasia = ko.observable(@Model.AbreviaFantasia.ToString().ToLower());

        self.update = function () {
            alert('Boom');
            $.ajax({
                type: "PUT",
                url: baseUri,
                data: self.Job,
                datatype: "json",
                contenttype: "application/json"
            })
                .done(function (data) {
                    //handleSuccessFunctionHERE(data);
                    alert('Magic');
                })
                .error(function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                    alert("fail");
                });
        };
    }

    function JobDetailsViewModel() {
        var self = this;
        var baseUri = '/Api/Pedidos/';
        self.Job = new JobViewModel();

    }

HTML

<label class="btn btn-primary" data-bind="css: {active:Job.AbreviaNome }">
      <input type="checkbox" data-bind="checked: AbreviaNome , onchange: Job.update" name="type" id="AbreviaNome "> Nome</input>
</label>

这永远不会触发更新功能。我也试过了:

<label class="btn btn-primary" data-bind="css: {active:Job.AbreviaNome }">
      <input type="checkbox" data-bind="checked: AbreviaNome , click: Job.update" name="type" id="AbreviaNome "> Nome</input>
</label>

这在JobViewModel中:

this.AbreviaNome.subscribe(function (newValue) {                
      alert('test');
}, this);

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

解决了问题,下面是绑定:

 <label class="btn btn-primary " data-bind="css: {active:Job.AbreviaNome}">
     <input type="checkbox" data-bind="checked: Job.AbreviaNome, event: {change: Job.update}" name="type" id="AbreviaNome">Nome/Razão</input>
 </label>

不确定这是最好的方法,但它有效。

答案 1 :(得分:0)

您应该使用subscribe而不是onchange处理程序。你提到你试过了,但你订阅了AbreviaNome而不是AbreviaLogradouro。