如何使用KnockoutJs将参数foreach从html传递到控制器

时间:2018-12-10 05:31:17

标签: jquery asp.net-mvc knockout.js

我想要从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。如何将参数敲除从html传递到javascript

1 个答案:

答案 0 :(得分:1)

当数组与foreach组合绑定一起使用时,它将当前迭代对象用作绑定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

相关问题