解决ASP MVC问题的对话

时间:2015-09-09 14:07:01

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

我是KnockoutJS的新手,我在解决利用Knockout数据绑定的最佳方法时遇到了一些问题。 Fiddle

我当前的项目使用对话框弹出窗口,然后填充值表等内容。但是目前,我只是将值从对话框复制到表中,方法是将值推送到Knockout observableArray。必须有一种方法可以简化这个过程(我有至少8个这类对话框,有些有15个以上的字段!)

<h4>Affiliations</h4>
<table id="AffiliationsTable" data-bind="foreach: affiliations">
    <thead>
        <tr>
            <td>Organization Name</td>
            <td>Affiliation Role</td>
        </tr>
    </thead>
    <tr>
        <td>
            <input data-bind="value: OrganizationName, attr: {name: 'Affiliations[' + $index() + '].OrganizationName'}">
        </td>
        <td>
            <input data-bind="value: AffiliationRole, attr: {name: 'Affiliations[' + $index() + '].AffiliationRole'}">
        </td>
    </tr>
</table>
<div id="dialogAffiliation" data-bind="dialog: {autoOpen: false, title: 'Affiliation' }, dialogVisible: isOpen">
    <label for="OrganizationName">Organization Name</label>
    <input type="text" name="OrganizationName" value="" class="text ui-widget-content ui-corner-all" id="OrganizationNameInsert">
    <label for="AffiliationRole">Affiliation Role</label>
    <input type="text" name="AffiliationRole" value="" class="text ui-widget-content ui-corner-all" id="AffiliationRoleInsert"><br />
    <button data-bind="click: addAffiliation">Save</button>
</div>

<div>
    <button data-bind="click: open">Add Affiliations</button>
</div>

KO代码有望成为最大的变化,但我似乎无法想到改进。也许用一个observable填充对话框,该observable在save-click时被移动到表DOM。或者更聪明的东西。任何建议将不胜感激!

var viewModel = function() {
    var self = this;
    self.isOpen = ko.observable(false);
    self.open = function () {
        this.isOpen(true);
    };
    self.close = function () {
        this.isOpen(false);
    };
    self.affiliations = ko.observableArray([
            { OrganizationName: ko.observable('name'), AffiliationRole: ko.observable("role")}, { OrganizationName: ko.observable('name2'), AffiliationRole: ko.observable("role2") }
    ]);

    self.addAffiliation = function () {
        self.affiliations.push({ OrganizationName: document.getElementById("OrganizationNameInsert").value, AffiliationRole: document.getElementById("AffiliationRoleInsert").value });
        $("#dialogAffiliation").dialog('close');
    };
};

ko.applyBindings(new viewModel());

http://jsfiddle.net/timotheusg/8c8xhf55/

1 个答案:

答案 0 :(得分:1)

一般来说,我建议使用模型。它允许一致性,并且它增加了能够使用Knockout的映射插件传递和映射数据的好处。

var viewModel = {
    listOfObjects: ko.observableArray(),
    object: {
        affiliation: ko.observable(),
        name: ko.observable(),
        title: ko.observable()

}

将表单绑定到“object”,并且save按钮将调用类似于:

的函数
// Turn object into plain JS object (there is also a toJSON)
var formData = ko.mapping.toJS(viewmodel.object);
// Push into array
listOfObjects.push(ko.mapping.fromJS(formData, mapping));

参考:http://knockoutjs.com/documentation/plugins-mapping.html

值得注意的是,您需要下载并包含映射插件的源代码才能使用此功能。它是由KO的首席开发人员创建的,我相信。