In this section, you will add features that allow users to create 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 ()}varAuthorsuri ='/api/authors/'; function getauthors() {Ajaxhelper (Authorsuri,' GET '). Done ( function (data) { Self. authors (data); });} Self. Addbook = function (formelement) { varBook = {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:
<div class="col-md-4"> <!-- TODO: Add new book --></div>
To:
<Div class="Col-md-4"><Div class="Panel Panel-default"> <Div class="Panel-heading"> <H2class="Panel-title">add bookDiv> <Div class="Panel-body"> <formclass="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>
This code creates a form that is used to submit a new author. The value of the Author drop-down box is data-bound to the authors of the view model. For other form inputs, these values are data-bound to the Newbook property of the view model.
The commit event on this form is data bound to the Addbook function:
class="form-horizontal"data-bind="submit: addBook">
This Addbook function reads the current value in the data-bound form input and creates a JSON object. The JSON object is then post to/api/books.
Web API Series Tutorial 3.9-Combat: Working with data (adding new entries to the database)