0

附加文件示例:http: //jsfiddle.net/brux88/9fzG4/1/

嗨,我开始在 asp.net mvc 项目中使用 knockoutjs。

我有一个看法:

 <button  data-bind='click: load'>Load</button>


<table>
            <thead>
                <tr>
                    <th>Cliente</th>
                    <th>Colli</th>
                    <th>Tara</th>
                    <th>Peso Tara</th>
                    <th> </th>
                </tr>
            </thead>
            <tbody data-bind='foreach: righe'>
                <tr>
                    <td>
                        <select  data-bind="
                           value: selectedCli,
                           options:  clienteList,
                           optionsText: function(item) { return item.Rscli + '-' + item.Codcli },
                           optionsCaption: '--Seleziona un Cliente--'"
                           style=" width: 150px">
                        </select>
                     </td>
                    <td >
                        <input data-bind='value: Ncolli' />
                    </td>

                    <td>
                        <select data-bind="value: selectedTara,
                                          options:  taraList,
                                          optionsText:  function(item) { return item.Destara  + 

'-' + item.Codtara},
                        optionsCaption: '--Seleziona un Cliente--'"

                                style=" width: 150px">
                        </select>
                    </td>
                    <td >
                        <input  data-bind="value: Ptara" />
                    </td>


                    <td>
                        <a href='#' data-bind='click: $parent.rimuoviRiga'>Elimina</a>
                    </td>
                </tr>
            </tbody>
        </table>
        <button   data-bind='click: aggiungiRiga'>Aggiungi</button>
        <button  data-bind='click: salva'>Salva</button>
        <button  data-bind='click: annulla'>Annulla</button>​

我的数据数据库结果:

[{"Codcli":4,"Rscli":"antonio","Codtart":"1002","Despar":"ciliegino","Ncolli":10,"Pcolli":100,"Codtara":"03","Destara":"","Ptara":82,"Pnetto":18,"Prezzo":1},{"Codcli":1,"Rscli":"bruno","Codtart":"1001","Despar":"pomodoro","Ncolli":10,"Pcolli":100,"Codtara":"03","Destara":"","Ptara":10,"Pnetto":90,"Prezzo":1}]

我的视图模型淘汰赛:

        <script type="text/javascript">
  var listCli= [{Codcli: 1,Rscli: "Bruno"},{Codcli: 2,Rscli: "Pippo"},{Codcli: 3,Rscli: "Giacomo"}];
var listTa= [{Codtara: 01,Destara: "Plastica",Pertara:4},{Codtara: 02,Destara: "Legno",Pertara:6},{Codtara: 03,Destara: "Ploto",Pertara:8}];

var mydataserver = [{"Codcli":3,"Rscli":"Giacomo","Ncolli":10,"Codtara":"03","Destara":"Legno","Ptara":82},{"Codcli":1,"Rscli":"Bruno","Ncolli":10,"Codtara":"02","Destara":"Plastica","Ptara":10}];

 var RigaOrdine = function () {
     var self = this;
                self.selectedCli = ko.observable();
                self.clienteList = ko.observableArray(listCli);            
                self.Ncolli = ko.observable();
                self.selectedTara = ko.observable();
                self.taraList = ko.observableArray(listTa);
                self.Ptara = ko.observable();


                self.Ncolli.subscribe(function () {
                    self.Ptara(self.Ncolli() ? self.selectedTara().Pertara * self.Ncolli() : 0);
                });



                self.selectedTara.subscribe(function () {
                    self.Ptara(self.Ncolli() ? self.selectedTara().Pertara * self.Ncolli() : self.selectedTara().Pertara);
                });
            };


            var Ordine = function () {
                var self = this;
                self.righe = ko.observableArray([new RigaOrdine()]); // Put one line in by default



                // Operations
                self.aggiungiRiga = function () { 
                    self.righe.push(new RigaOrdine());
                        };
                self.rimuoviRiga = function (riga) { 
                    self.righe.remove(riga);
                        };


                self.salva = function() {
                 var righe = $.map(self.righe(), function (riga) {
                        return riga.selectedCli() ? {
                            Codcli: riga.selectedCli().Codcli,
                            Rscli: riga.selectedCli().Rscli,
                            Ncolli: riga.Ncolli(),
                            Codtara: riga.selectedTara().Codtara,
                            Ptara: riga.Ptara(),
                            } : undefined;
                    });
                    alert( ko.toJSON(righe));
                    //save to server
                   /* $.ajax({
                        url: "/echo/json/",
                        type: "POST",
                        data: ko.toJSON(righe),
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: function(data) {
                        }
                    });*/
                    self.righe([new RigaOrdine()]);
                };

                //load from server
                self.load = function() {
                    $.ajax({ url: '/echo/json/', 
                      accepts: "application/json", 

                      cache: false, 
                      statusCode: { 

                        200: function (data) {
                            alert(ko.toJSON(mydataserver));
                            //i do not know apply to viewmodel
                        }, 
                        401: function (jqXHR, textStatus, errorThrown) { 
                          alert('401: Unauthenticated'); 
                         // self.location = "../../Account/Login.html?returnURL=/Index.html"; 
                        } 
                      } 
                    }); 


                };
                self.annulla = function() {
                    self.righe([new RigaOrdine()]);
                };



            };
            var viewmodel = new Ordine();
           ko.applyBindings(viewmodel);


​

    </script>

如果我想从数据库加载数据,我该怎么做?而有下拉列表

4

2 回答 2

0

你的问题有点弱,所以我会给你一个更笼统的答案。

要回答有关如何从数据库加载数据的问题,看来您已经走上了正确的道路。通常您使用 AJAX 请求来执行数据的异步请求。为此,knockoutJS 提供了以下功能:

$.getJSON("/some/url", function(data) { 
    // Now use this data to update your view models, 
    // and Knockout will update your UI automatically
})

来源: http: //knockoutjs.com/documentation/json-data.html

在提供的回调中,您将可以访问从服务器返回的数据。这取决于您的应用程序的逻辑您想要在这里做什么 - 对于某些应用程序,更新视图模型的状态以在视图中进行相应的更新可能是有意义的。

如果您的问题更具体,请详细说明。否则,我希望我能让你走上正轨。

于 2012-09-04T18:32:40.740 回答
0

如我所见..您可能需要一些好的练习来加载。我会和你分享我的。

好吧.. 将 Json 作为 JsonResult 返回。

    // POST: /Client/LoadClient
    [HttpPost]
    public JsonResult LoadClient(int? id)
    {
        if (id == null) return null;

        var client = _business.FindById((int) id);

        return Json(
            new
            {
                id = cliente.id,
                name = cliente.name,
                list = cliente.listOfSomething.Select(s => new {idItemFromList = s.idWhatever, nameItemFromList = s.nameWhatever})
            });

    }

JS

viewmodel.Client.prototype.LoadClient= function (id) {
var self = this;

if (id == 0) {
    return null;
}

$.ajax({
    url: actionURL("LoadClient", "Client"),
    data: { id: parseInt(id) },
    dataType: "json",
    success: function (result) {
        if (result != null)
            self.Load(result);
    }
});

加载方法。

viewmodel.Client.prototype.Load = function (result) {
var self = this;

self.idClient(result.id);
self.nameCliente(result.name);
self.ListOfSomething(result.list);
};

和..

ko.applyBinding( yourModel );

如您所见,我正在使用原型,这也是一个好习惯。

于 2012-09-04T18:57:59.760 回答