Search code examples
javascriptknockout.jsplunkerkogrid

KO Grid unable to save data from edited cell - with Plunker


I have an Asp.Net MVC website for which I've started to use the knockoutjs kogrid to display grids of data.

For one particular grid, I would like the user to be able to edit an Email Address column. On clicking a save button the edited value should persist to a database.

I am able to present the grid ok, and on selecting a row the user can type into the required cell. My problem is, I haven't figured out how to reference the changed cell value.

Here is the definition for my grid options:

var emailCellTemplate = '<div><input type=\"text\" data-bind=\"visible: $parent.selected(), value: $parent.entity[$data.field]" /><span data-bind=\"visible: !$parent.selected(), text: $parent.entity[$data.field]\"></span></div>'
this.gridOptions = {
    height: 200,
    afterSelectionChange: function () { return true; },
    data: self.workflowRules,
    enablePaging: true,
    pagingOptions: self.pagingOptions,
    filterOptions: self.filterOptions,
    selectWithCheckboxOnly: true,
    selectedItems: self.selected,
    canSelectRows: true,
    displaySelectionCheckbox: true,
    columnDefs: [{ field: 'ReceivePortName', displayName: 'Receive Port', width: 130 },
                { field: 'MessageType', displayName: 'Message Type', width: 400 },
                { field: 'TriggerSource', displayName: 'Source', width: 150 },
                { field: 'TargetEmailAddress', displayName: 'Email', width: 180, cellTemplate: emailCellTemplate },
                { field: 'AssignedToName', displayName: 'Assigned To', width: 140 },
    ]
};

$parent.entity[$data.field] is great for selecting the value that was loaded from the database but doesn't give me the edited value. When I place a breakpoint on the js code that runs when my Save to Database button is clicked, then I do get to see the edited value in WorkflowRules.TargetEmailAddress but I have't figured out how to bind to it.

I have created a plunk to help illustrate here: https://plnkr.co/edit/Ibc0WZwyb4melgNDzcUo

Could anyone please advise how I need to set my emailCellTemplate?


Solution

  • Thanks for the comments, I have now tracked down the cause of the bug.

    The problem was in my savetoDatabase function of my javascript controller. The controller did define an observeable this.workflowRules = ko.observableArray(vm.WorkflowRules); but within the saveToDatabase function it used the server view model when converting to JSON prior to calling the server controller var jsSaveModel = ko.toJS(vm);

    In order to fix this, I added an extra line to update the WorkflowRules array of the vm with the content of the observable before converting to JSON, so I now have

    vm.WorkflowRules = this.workflowRules();
    var jsSaveModel = ko.toJS(vm);