首页 文章

如何使用knockoutJs将参数foreach从html传递给控制器

提问于
浏览
1

我想从CSHTML解析参数foreach . 使用来自 knockout.js <div data-bind="foreach: viewPjsp(1)"> 的foreach .

javascipt的:

function ColumnInput(Id, NameColumn) {
  var self;
  self = this;
  self.Id = ko.observable(Id || null);
  self.NameColumn = ko.observable(NameColumn || null);
}

(function () {
'use strict';
function ElicensingPjspViewModel() {
    var self = this;

    self.viewPjsp = ko.observableArray([]);

    self.getViewPjsp = function (data, event) {
        var url;

        $.ajax({
            type: "GET",
            url: $.rootDir + 'PJSP/PjspEvaluationDetail?AspectId=1', --> here parameter I want to parsing
            success: function (data) {
                var result;
                console.log(data);

                result = ko.utils.arrayMap(data.permission, function (item) {
                    return new KolomInput(item.Id, item.NameColumn);
                });

                self.viewPjsp(result);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
    };
    self.getViewPjsp();
}

ko.applyBindings(new ElicensingPjspViewModel(), document.getElementById('pjsp_prinsipal'));
}());

Javascript 尚未使用参数 . 如何调用viewPjsp(1)然后使用参数 ?AspectId=xxxx 发送到ajax中的URL . 如何将参数knockout从html传递给javascript

1 回答

  • 1

    当数组与 foreach knockout绑定一起使用时,它使用当前迭代对象作为绑定的foreach html元素中包含的html标记的数据上下文 . 所以你可以做类似下面的代码片段 . 我添加了额外的功能,允许点击表格行以显示该人的ID . 我将留给您修改示例以满足您的需求 .

    function getData(data){
      alert("The Id of the person is " + data.id);
    }
    
    ko.applyBindings({
            people: [
                { firstName: 'Bert', lastName: 'Bertington', id: 1 },
                { firstName: 'Charles', lastName: 'Charlesforth', id: 2 },
                { firstName: 'Denise', lastName: 'Dentiste', id: 3 }
            ]
        });
    
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    
    <!-- example from here - https://knockoutjs.com/documentation/foreach-binding.html -->
    <table class="table">
        <thead>
            <tr><th>First name</th><th>Last name</th></tr>
        </thead>
        <tbody data-bind="foreach: people">
            <tr data-bind="click: getData">
                <td data-bind="text: firstName"></td>
                <td data-bind="text: lastName"></td>
            </tr>
        </tbody>
    </table>
    

    有关更好的解释,请查看此示例来自的淘汰文档 . Knockout "foreach" Binding

相关问题