1
votes

On initial page load, my data gets loaded fine. I have a delete function which calls my controller through .ajax and deletes the item in the database OK, and then sends back the new list of JSON items. Everything works until I call ko.mapping.fromJS(data.newData, viewModel) and then the page just stalls out with no error messages. If I add in an alert(data.newData) I see the correct Json. Following is the code, can anyone see what I am doing wrong?

<script>
var initialData = @Html.Raw(Json.Encode(Model));

var viewModel = {
    trainingDocs : ko.observableArray(initialData)
};

function deleteDoc(doc) {
    $.ajax({
        url: "/Admin/_DeleteTrainingDocument/"+doc.TrainingDocumentId,
        type: "POST",
        data: "",
        success: function (data) {
            if (data.Result) {
                $("#userMessage").html("<img src='/content/Status_1.png' align='bottom' />" + data.Message);
                ko.mapping.fromJS(data.newData, viewModel);
            } else {
                $("#userMessage").html("<img src='/content/Status_0.png' align='bottom' />" + data.Message);
            }
        },
        error: function (jqXhr, textStatus, errorThrown) {
            alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
        },
        complete: function () {
        }
    });
};

ko.applyBindings(viewModel, document.body);
</script>

<table class="agent-info">
<thead>
    <tr> 
        <th>Title</th> 
        <th>Action</th> 
    </tr> 
</thead>
<tbody data-bind="foreach: trainingDocs">
    <tr> 
        <td><span data-bind="text:Title"></span></td> 
        <td><a href="#" id="whiteLinks" data-bind="click: function() { if(confirm('Are you sure you want to delete '+$data.Title+'?')) deleteDoc($data) }">delete</a></td>
    </tr> 
</tbody>
</table>​
<div id="userMessage">
    Results
</div>
1
Can you also add your html showing the databindings? Even better would be a jsfiddle showing your error - peacemaker
OK peacemaker, I edited my question and added the html. I'm brand new to Knockout.js, so I've not gotten familiar enough with jsfiddle yet, even though I have seen some examples of it. - Bill McGrath

1 Answers

2
votes

I am not sure of the exact structure being returned from your AJAX call, but if to update your existing data you either need to:

  • create your original observableArray using the mapping plugin like:

    var viewModel = { trainingDocs : ko.mapping.fromJS(initialData) };

  • or pass in empty mapping options when updating in your callback like:

    ko.mapping.fromJS(data.newData, {}, viewModel);

Also, for the update call, I would pay close attention to what data.newData contains, because I would suspect that you may need to use viewModel.trainingDocs instead of just viewModel, if the data is the actual array.