0

我在 Asp.net mvc4 中工作并使用 web api 尝试将 WebApi Json Result 绑定到 Knockout Js 但下面的绑定未在文本框或跨度中显示任何值

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

但价值并未显现。

JSON 结果

Json 收到的结果如下。

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

我的 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>
4

1 回答 1

3

看起来您尝试传递给 self.models 的 JSON 对象的范围不正确。我认为您想要代表角色的值列表。getJSON 调用应如下所示。

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

看看这个小提琴:http: //jsfiddle.net/Zebnc/12/

不过,我和经理先生有同样的问题。属性名称中的 $ 是怎么回事?

于 2013-08-12T19:30:22.113 回答