ineffable p
ineffable p

Reputation: 1189

Knockout Js Binding

I am working in Asp.net mvc4 and using web api trying to bind WebApi Json Result to Knockout Js but the below binding not showing any value in text box or span

<input type="text" data-bind="value: $data.RoleName"/>
<span data-bind="value: $data.RoleId"></span>

But the value is not showing.

JSON Result

Json received result as below.

{
  "$id": "1",
  "$values": [
    {
      "$id": "2",
      "RoleId": 1,
      "RoleName": "admin",
      "Users": {
        "$id": "3",
        "$values": []
      }
    },
    {
      "$id": "4",
      "RoleId": 2,
      "RoleName": "user",
      "Users": {
        "$id": "5",
        "$values": []
      }
    }
  ]
}

My HTML

<!DOCTYPE html>

<html>
    <head>
        <meta charset="utf-8" />
        <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="robots" content="noindex, nofollow">
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />     
        <link href="/Content/bootstrap.css" rel="stylesheet"/>
        <link href="/Content/bootstrap-responsive.css" rel="stylesheet"/>
        <link href="/Content/site.css" rel="stylesheet"/>
        <script src="/Scripts/modernizr-2.6.2.js"></script>

           <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="/scripts/html5shiv.js"></script>
    <![endif]-->

        <!-- Layout Fix and Error Script -->
        <script type="text/javascript" src="/Scripts/header-script.js"> </script>
        <!-- The fav icon -->
        <link rel="shortcut icon" href="/Content/images/favicon.ico">
        <link rel="apple-touch-icon" href="/Content/images/Logo.png">


    </head>
    <body>

<div class="container">

<div class="container-fluid">
   <ul id="update-models" data-bind="foreach: models">
        <li>
            <div>
                <div class="item">ID</div> 
                <span data-bind="value: $data.RoleId"></span>
            </div>
            <div>
                <div class="item">Name</div> 
                 <input type="text" data-bind="value: $data.RoleName"/>
            </div> 
            <div>
                <input class="btn btn-primary" type="button" value="Update" data-bind="click: $root.update"/>
                <input class="btn btn-danger" type="button" value="Delete Item" data-bind="click: $root.requestDelConfirm"/>
            </div>
        </li>
    </ul>
</div>

<div id="error-container" class="none">
    <div class="alert alert-error">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <h4>Oops..</h4>
        <p>Something went wrong. Here's the error message:</p>
        <p data-bind="text: errorMessage"></p>
    </div>
</div>


<div id="del-confirm" class="modal hide fade" tabindex="-1" role="dialog"  aria-labelledby="del-confirm-label" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" 
                data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="del-confirm-label">Confirm Delete</h3>
    </div>
    <div class="modal-body">
        <p>Are you sure you want to delete the selected Model?</p>
        <p class="alert alert-error push-down"><strong>Note:</strong> 
            There is no undo for this action.</p>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

        <button class="btn btn-primary" data-bind="click: remove">Delete</button>
    </div>
</div>
            <footer>
                <div class="navbar-fixed-bottom">
                    <p class="pull-left">
                        Copyright © 2013
                    </p>
                    <p class="pull-right"><img src="/Content/images/Logo.png" /></p>
                </div>
            </footer>     
        </div>


        <script src="/Scripts/jquery-2.0.3.js"></script>
        <script src="/Scripts/bootstrap.js"></script>
        <script src="/Scripts/knockout-2.3.0.debug.js"></script>
        <script src="/Scripts/underscore.js"></script>
        <script src="/Scripts/H5F.js"></script>
        <script type="text/javascript">
            function ViewModel() {
                var self = this;
                self.models = ko.observableArray();

                var baseUri = '/api/Roles';
                self.errorMessage = ko.observable();

                self.showError = function(error) {
                    $('#error-container').fadeIn();
                };
                self.currentModel = {};
                self.requestDelConfirm = function(model) {
                    self.currentModel = model;
                    $('#del-confirm').modal();
                };

                self.create = function(formElement) {
                    // If valid, post the serialized form data to the web api
                    $(formElement).validate();
                    if ($(formElement).valid()) {
                        $.post(baseUri, $(formElement).serialize(), null, "json")
                            .done(function(o) { self.models.push(o); });
                    }
                };
                self.update = function(model) {
                    $.ajax({ type: "PUT", url: baseUri + '/' + model.Id, data: model });
                };
                self.remove = function(model) {
                    // First remove from the server, then from the UI
                    $.ajax({ type: "DELETE", url: baseUri + '/' + model.Id })
                        .done(function() { self.models.remove(model); })
                        .error(function(error) { self.showError(error); })
                        .always(function() { $('#del-confirm').modal('hide'); });
                };
                $.getJSON(baseUri, self.models);
            }

            $(document).ready(function() {
                ko.applyBindings(new ViewModel());
            });

        </script>

    </body>
</html>

Upvotes: 0

Views: 394

Answers (1)

PeaceFrog
PeaceFrog

Reputation: 717

It looks like the scope of the JSON object you are trying to pass to self.models is not correct. I think you want the list of values that represent the Roles. The getJSON call should look something like this.

$.getJSON(baseUri, function(data) {
    self.models(data.$values);
});

Take a look at this fiddle: http://jsfiddle.net/Zebnc/12/

I have the same question as Mr. Manager though. What's up with the $ in the property names?

Upvotes: 3

Related Questions