Cubicle.Jockey
Cubicle.Jockey

Reputation: 3328

Knockout Mapping attempt not mapping with JSON responses

I am new to knockout and cannot seem to get a simple mapping to work at all. I am in an MVC4 C#.

My View looks like such:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Index";
}

<h2>Simple Mapping Example</h2>

The time on the server is: <span data-bind="text: ServerTime"></span>
and <span data-bind="text: NumberOfUsersConnected"></span> user(s) are connected.

@section Scripts
{
    <script type="text/javascript">

        function ViewModel() {
            var self = this;

            self.ServerTime = ko.observable();
            self.NumberOfUsersConnected = ko.observable();
        }

        var vm = new ViewModel();
        ko.applyBindings(vm);

        $.getJSON('/Mapping/GetServerInfo', function(data) {
            ko.mapping.fromJSON(data, {}, vm);
        });

    </script>
}

Example JSON that is returned from the controller call 'Mapping/GetServerInfo' is:

{"ServerTime":"2013-03-13T14:24:10.5675104-07:00","NumberOfUsersConnected":5}

For the data-binds I have tried text and value, neither one causes any data to be bound and displayed.

Am I missing something really obvious?

As per the question in the comments yes this is what is in my Layout.

<script type="text/javascript" src="~/Scripts/knockout-2.2.1.js"></script>
<script type="text/javascript" src="~/Scripts/knockout.mapping-latest.js"></script>

Thanks

Upvotes: 1

Views: 886

Answers (1)

nemesv
nemesv

Reputation: 139758

From the $.getJSON documentation

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.

So your the data variable is holding an already parsed object so you need to use the ko.mapping.fromJS method:

$.getJSON('/Mapping/GetServerInfo', function(data) {
   ko.mapping.fromJS(data, {}, vm);
});

Upvotes: 3

Related Questions