<table> <thead> <tr> <th>Id</th> <th>Name</th> <th>Age</th> <th>Comments</th> <th></th> <th></th> </tr>
</thead> <tbody data-bind="foreach: customers"> <tr> <td data-bind="text: Id"></td> <td data-bind="text: Name"></td> <td data-bind="text: Age"></td> <td data-bind="text: Comment"></td> <td><button data-bind="click: $root.deleteCustomer" >Delete</button></td> </tr> </tbody></table>
<table> <tr> <td>Name</td> <td> <input type="text" data-bind="value: Name" id="txt_Name"/></td> </tr> <tr> <td>Age</td> <td> <input type="text" data-bind="value: Age" /></td> </tr> <tr> <td>Comments</td> <td> <input type="text" data-bind="value: Comment" /></td> </tr></table><input type="button" value="Add" data-bind="click: $data.addCustomer" />
/// <reference path="../Scripts/jquery-1.8.2.js>/// <reference path="../Scripts/knockout-2.2.0.js>$(document).ready(function () {
var cusVM = new customerViewModel(); ko.applyBindings(cusVM, document.getElementById("displayMode2")); ko.applyBindings(cusVM, document.getElementById("createMode2"));});function customerViewModel() { var self = this; self.Name = ko.observable(); self.Id = ko.observable(); self.Age = ko.observable(); self.Comment = ko.observable(); self.customers = ko.observableArray(); var customerData = { Id: self.Id, Name: self.Name, Age: self.Age, Comment: self.Comment };
GetCustomers(); function GetCustomers() { $.ajax({ type: "GET", url: "/api/customer", contentType: "application/json;charset=utf-8", dataType: "json", success: function (data) { self.customers(data); }, error: function (error) { alert(error.status); } }); } //$.getJSON("/api/customer", self.customers); self.addCustomer = (function () { $.ajax({ type: "POST", url: "/api/customer", contentType: "application/json", data: ko.toJSON(customerData), success: function (data) { GetCustomers();
}, error: function (error) { alert(error.status); }
}); self.Name = ko.observable("");
});
self.deleteCustomer = (function (customer) { var cfrm = confirm("Are you sure you want to delete?"); if (cfrm == true) { $.ajax({ type: "DELETE", url: "/api/customer/" + customer.Id, success: function (data) { //alert(customer.Id + " is deleted"); GetCustomers(); }, error: function (error) { alert(error.status); }
}); } });
}