將新項目新增至資料庫

下載已完成的專案

在本節中,您將新增使用者建立新書籍的能力。 在 app.js中,將下列程式碼新增至檢視模型:

self.authors = ko.observableArray();
self.newBook = {
    Author: ko.observable(),
    Genre: ko.observable(),
    Price: ko.observable(),
    Title: ko.observable(),
    Year: ko.observable()
}

var authorsUri = '/api/authors/';

function getAuthors() {
    ajaxHelper(authorsUri, 'GET').done(function (data) {
        self.authors(data);
    });
}

self.addBook = function (formElement) {
    var book = {
        AuthorId: self.newBook.Author().Id,
        Genre: self.newBook.Genre(),
        Price: self.newBook.Price(),
        Title: self.newBook.Title(),
        Year: self.newBook.Year()
    };

    ajaxHelper(booksUri, 'POST', book).done(function (item) {
        self.books.push(item);
    });
}

getAuthors();

在 Index.cshtml 中,取代下列標記:

<div class="col-md-4">
    <!-- TODO: Add new book -->
</div>

替換為:

<div class="col-md-4">
<div class="panel panel-default">
  <div class="panel-heading">
    <h2 class="panel-title">Add Book</h2>
  </div>

  <div class="panel-body">
    <form class="form-horizontal" data-bind="submit: addBook">
      <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: newBook.Author"></select>
        </div>
      </div>

      <div class="form-group" data-bind="with: newBook">
        <label for="inputTitle" class="col-sm-2 control-label">Title</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="inputTitle" data-bind="value:Title"/>
        </div>

        <label for="inputYear" class="col-sm-2 control-label">Year</label>
        <div class="col-sm-10">
          <input type="number" class="form-control" id="inputYear" data-bind="value:Year"/>
        </div>

        <label for="inputGenre" class="col-sm-2 control-label">Genre</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="inputGenre" data-bind="value:Genre"/>
        </div>

        <label for="inputPrice" class="col-sm-2 control-label">Price</label>
        <div class="col-sm-10">
          <input type="number" step="any" class="form-control" id="inputPrice" data-bind="value:Price"/>
        </div>
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
  </div>
</div>
</div>

此標記會建立表單來提交新的作者。 作者下拉式清單的值資料會繫結至檢視模型中可觀察的 authors。 對於其他表單輸入,值資料會繫結至檢視模型的 newBook 屬性。

表單上的提交處理常式會繫結至 addBook 函式:

<form class="form-horizontal" data-bind="submit: addBook">

addBook 函式會讀取資料繫結表單輸入的目前值,以建立 JSON 物件。 然後將 JSON 物件 POST 到 /api/books