1

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

2
  • 1
    Have you referenced KO and KO.mapping in your layout? Does the @RenderSection("Scripts") come after the @RenderBody and script includes? Commented Mar 13, 2013 at 21:34
  • Updated original question. Thanks Commented Mar 13, 2013 at 21:35

1 Answer 1

3

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I figured this out. Thanks for the reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.