0

I have an application that returns a JSON object via ajax. I am trying to pass these objects to the DOM but something is not working. Here is the knockout code

function PanelViewVM() {
    var self = this;


    self.Panel = ko.observable("test");
    self.Source = ko.observable();


    self.SelectPanel = function () {

        $.ajax("/DPanel/FillIndex", {

            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {


                self.Panel = data.PanelDetails[0].Panel;
                self.Source = data.PanelDetails[0].Source;



                //ko.mapping.fromJS(data.PanelDetails, {}, self.PanelDetails);

            },
            error: function (data) {
                console.log(data);
            }
        });

    };

    self.SelectPanel();

};

ko.applyBindings(new PanelViewVM());

When I run the code in VS and place a break at the end of the ajax request, it states that self.Source and self.Panel have data assigned. However, this does not get reflected in the DOM. I have also put a "Test" placeholder in the panel observable. This passes to the DOM as expected.

@using System.Web.Optimization
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div class="row">
    <p>Panel:<strong data-bind="text: Panel"></strong></p>
    <p>Source:<strong data-bind="text: Source"></strong></p>



</div>





@section Scripts {

@Scripts.Render("~/bundles/knockout")
@Scripts.Render("~/Scripts/ViewModel/PanelViewVM.js")

    } 

Any ideas?

user1781272
  • 862
  • 2
  • 14
  • 25

1 Answers1

1

You're replacing the observable object with the plain value returned from the ajax call. You'll need to use the current observable function to update the value like so (from memory, but I'm confident it'll work).

success: function (data) {
    self.Panel(data.PanelDetails[0].Panel);
    self.Source(data.PanelDetails[0].Source);
},
DoctorMick
  • 6,703
  • 28
  • 26