[Web API series tutorial] 3.9-practice: process data (add new entries to the database)
This section describes how to create a new book. In app. js, add the following code to the view model:
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();
In Index. cshtml, replace the following code:
<code class=" hljs xml"> <!--{cke_protected}{C}%3C!%2D%2D%20TODO%3A%20Add%20new%20book%20%2D%2D%3E--></code>
To:
<code class=" hljs applescript"> </code>
Add Book
<form class="form-horizontal" data-bind="submit: addBook"><code class="hljs applescript"><label class="col-sm-2 control-label" for="inputAuthor">Author</label> <select data-bind="options:authors, optionsText: 'Name', value: newBook.Author"></select> <label class="col-sm-2 control-label" for="inputTitle">Title</label> <input class="form-control" data-bind="value:Title" id="inputTitle" type="text" /> <label class="col-sm-2 control-label" for="inputYear">Year</label> <input class="form-control" data-bind="value:Year" id="inputYear" type="number" /> <label class="col-sm-2 control-label" for="inputGenre">Genre</label> <input class="form-control" data-bind="value:Genre" id="inputGenre" type="text" /> <label class="col-sm-2 control-label" for="inputPrice">Price</label> <input class="form-control" data-bind="value:Price" id="inputPrice" step="any" type="number" /><button class="btn btn-default" type="submit">Submit</button></code></form>
This Code creates a form for submitting a new author. The value in the drop-down list of the author is bound to the authors of the view model. For other form inputs, these values are bound to the newBook attribute of the view model.
The submission event on this form is bound to the addBook function by data:
<form class="form-horizontal" data-bind="submit: addBook"> </form>
This addBook function reads the current value in the data binding form input and creates a JSON object. Then the JSON object will be POST to/api/books.