敲除选项绑定多个模型的控件

时间:2014-07-06 19:57:07

标签: c# javascript asp.net api knockout.js

我在本教程中工作 http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/part-9

我想生成编辑表单,其中作者是下拉列表并且当前作者被选中我使用类似于此的表单

function getAllbooks() {
          ajaxHelper(baseUri, 'GET').done(function (data) {
              self.books(data);
          });
 <ul id="update-book" data-bind="foreach: books">
    <li>
        <div>
            <div class="item">Book ID</div> <span data-bind="text: $data.ID"></span>

        </div>
 <div class="form-group">
    <label for="inputAuthor" class="col-sm-2 control-label">Author</label>
    <div class="col-sm-10">
      <select data-bind="options:authors, optionsText: 'Name', value: $data.AuthorId"></select>
    </div>
  </div>
        <div>
            <div class="item">Genre</div> 
            <input type="text" data-bind="value: $data.Genre"/>


        </div> 
 <div>
            <div class="item">Price</div> 
            <input type="text" data-bind="value: $data.Price"/>


        </div> 
 <div>
            <div class="item">Title</div> 
            <input type="text" data-bind="value: $data.Title"/>


        </div> 
<div>
            <div class="item">Year</div> 
            <input type="text" data-bind="value: $data.Year"/>


        </div> 
<div>
            <input type="button" value="Update" data-bind="click: $root.update"/>
            <input type="button" value="Delete Item" data-bind="click: $root.remove"/>
        </div>
    </li>
</ul>
</div>

但我有javascript错误作者未定义,因为它在foreach书中,我不确定何时使用了值:$ data.AuthorId会给我id或不

1 个答案:

答案 0 :(得分:0)

我只能猜测您的数据结构,如果author对象有Id

你应该做

<select data-bind="options: $root.authors,
  optionsText: 'Name',
  optionsValue: 'Id',
  value: AuthorId"></select>

但还有另一个问题,如果您的book.AuthorId不是ko.observable(这是我对您的代码的猜测),当用户选择不同的作者时,上述绑定不会更新它的值。