Академический Документы
Профессиональный Документы
Культура Документы
I n previous article, I have explained Knockout CRUD Operations using MVC4. In this article, I will
demonstrate, how to use Knockout with Web API for CRUD (Create, Read, Update, Delete) Operations.
Product.cs
IProductRepository.cs
1. interface IProductRepository
2. {
3. IEnumerable<Product> GetAll();
4. Product Get(int id);
5. Product Add(Product item);
6. bool Update(Product item);
7. bool Delete(int id);
8. }
ProductRepository.cs
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 1/17
6/27/2014 Web API CRUD Operations with Knockout
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 2/17
6/27/2014 Web API CRUD Operations with Knockout
47.
48. // TO DO : Code to update record into database
49. int index = products.FindIndex(p => p.Id == item.Id);
50. if (index == -1)
51. {
52. return false;
53. }
54. products.RemoveAt(index);
55. products.Insert(index,item);
56.
57. return true;
58. }
59.
60. public bool Delete(int id)
61. {
62. // TO DO : Code to remove the records from database
63. products.RemoveAll(p => p.Id == id);
64.
65. return true;
66. }
67. }
HomeController.cs
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 3/17
6/27/2014 Web API CRUD Operations with Knockout
7. return repository.GetAll();
8. }
9.
10. public Product PostProduct(Product item)
11. {
12. return repository.Add(item);
13. }
14.
15. public IEnumerable PutProduct(int id, Product product)
16. {
17. product.Id = id;
18. if (repository.Update(product))
19. {
20. return repository.GetAll();
21. }
22. else
23. {
24. return null;
25. }
26. }
27.
28. public bool DeleteProduct(int id)
29. {
30. if (repository.Delete(id))
31. {
32. return true;
33. }
34. else
35. {
36. return false;
37. }
38.
39. }
40. }
Product.cshtml
1. @{
2. ViewBag.Title = "Products' List";
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 4/17
6/27/2014 Web API CRUD Operations with Knockout
3. }
4.
5. @section scripts {
6. <style type="text/css">
7. body {
8. margin: 20px;
9. font-family: "Arial", "Helventica", sans-serif;
10. }
11.
12. label {
13. width: 80px;
14. display: inline-block;
15. }
16.
17. button {
18. display: inline-block;
19. outline: none;
20. cursor: pointer;
21. text-align: center;
22. text-decoration: none;
23. padding: .4em 1.1em .4em;
24. color: #fef4e9;
25. border: solid 1px #006fb9;
26. background: #1276bb;
27. }
28.
29. button:hover {
30. text-decoration: none;
31. background: #282828;
32. border: solid 1px #000;
33. }
34.
35. table {
36. padding-top: 1em;
37. }
38.
39. thead, tfoot {
40. font-weight: 600;
41. }
42.
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 5/17
6/27/2014 Web API CRUD Operations with Knockout
43. th, td {
44. padding: .1em .5em;
45. text-align: left;
46. }
47.
48. td li, td ul {
49. margin: 0;
50. padding: 0;
51. }
52.
53. td li {
54. display: inline;
55. }
56.
57. td li::after {
58. content: ',';
59. }
60.
61. td li:last-child::after {
62. content: '';
63. }
64. </style>
65. <script src="~/Scripts/knockout-2.2.0.js"></script>
66. <script src="@Url.Content("~/Scripts/knockout-2.2.0.debug.js")"
type="text/javascript"></script>
67. <script type="text/javascript">
68.
69. function formatCurrency(value) {
70. return "$" + value.toFixed(2);
71. }
72.
73. function ProductViewModel() {
74.
75. //Make the self as 'this' reference
76. var self = this;
77. //Declare observable which will be bind with UI
78. self.Id = ko.observable("");
79. self.Name = ko.observable("");
80. self.Price = ko.observable("");
81. self.Category = ko.observable("");
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 6/17
6/27/2014 Web API CRUD Operations with Knockout
82.
83. var Product = {
84. Id: self.Id,
85. Name: self.Name,
86. Price: self.Price,
87. Category: self.Category
88. };
89.
90. self.Product = ko.observable();
91. self.Products = ko.observableArray(); // Contains the list of products
92.
93. // Initialize the view-model
94. $.ajax({
95. url: 'api/product',
96. cache: false,
97. type: 'GET',
98. contentType: 'application/json; charset=utf-8',
99. data: {},
100. success: function (data) {
101. self.Products(data); //Put the response in ObservableArray
102. }
103. });
104.
105. // Calculate Total of Price After Initialization
106. self.Total = ko.computed(function () {
107. var sum = 0;
108. var arr = self.Products();
109. for (var i = 0; i < arr.length; i++) {
110. sum += arr[i].Price;
111. }
112. return sum;
113. });
114.
115. //Add New Item
116. self.create = function () {
117. if (Product.Name() != "" && Product.Price() != "" && Product.Category() !=
"") {
118. $.ajax({
119. url: 'api/product',
120. cache: false,
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 7/17
6/27/2014 Web API CRUD Operations with Knockout
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 8/17
6/27/2014 Web API CRUD Operations with Knockout
161. }
162. }
163.
164. // Edit product details
165. self.edit = function (Product) {
166. self.Product(Product);
167.
168. }
169.
170. // Update product details
171. self.update = function () {
172. var Product = self.Product();
173. var id = Product.Id;
174.
175. $.ajax({
176. url: 'api/product/' + id,
177. cache: false,
178. type: 'PUT',
179. contentType: 'application/json; charset=utf-8',
180. data: ko.toJSON(Product),
181. success: function (data) {
182. self.Products.removeAll();
183. self.Products(data); //Put the response in ObservableArray
184. self.Product(null);
185. alert("Record Updated Successfully");
186.
187. }
188. })
189. .fail(
190. function (xhr, textStatus, err) {
191. alert(err);
192. });
193. }
194.
195. // Reset product details
196. self.reset = function () {
197. self.Name("");
198. self.Price("");
199. self.Category("");
200. }
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 9/17
6/27/2014 Web API CRUD Operations with Knockout
201.
202. // Cancel product details
203. self.cancel = function () {
204. self.Product(null);
205.
206. }
207. }
208. var viewModel = new ProductViewModel();
209. ko.applyBindings(viewModel);
210.
211. </script>
212. }
213.
214. <div id="body">
215.
216. <h2>Knockout CRUD Operations with MVC4</h2>
217.
218. <h3>List of Products</h3>
219.
220. <table id="products1" data-bind="visible: Products().length > 0">
221. <thead>
222. <tr>
223. <th>ID</th>
224. <th>Name</th>
225. <th>Category</th>
226. <th>Price</th>
227. <th>Actions</th>
228. </tr>
229. </thead>
230. <tbody data-bind="foreach: Products">
231. <tr>
232. <td data-bind="text: Id"></td>
233. <td data-bind="text: Name"></td>
234. <td data-bind="text: Category"></td>
235. <td data-bind="text: formatCurrency(Price)"></td>
236.
237. <td>
238. <button data-bind="click: $root.edit">Edit</button>
239. <button data-bind="click: $root.delete">Delete</button>
240.
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 10/17
6/27/2014 Web API CRUD Operations with Knockout
241. </td>
242.
243. </tr>
244. </tbody>
245. <tfoot>
246. <tr>
247. <td></td>
248. <td></td>
249. <td>Total :</td>
250. <td data-bind="text: formatCurrency($root.Total())"></td>
251. <td></td>
252. </tr>
253. </tfoot>
254. </table>
255. <br />
256. <div style="border-top: solid 2px #282828; width: 430px; height:
10px"> </div>
257.
258. <div data-bind="if: Product">
259. <div>
260. <h2>Update Product</h2>
261. </div>
262. <div>
263. <label for="productId" data-bind="visible: false">ID</label>
264. <label data-bind="text: Product().Id, visible: false"></label>
265.
266. </div>
267. <div>
268. <label for="name">Name</label>
269. <input data-bind="value: Product().Name" type="text" title="Name" />
270. </div>
271.
272. <div>
273. <label for="category">Category</label>
274. <input data-bind="value: Product().Category" type="text" title="Category" />
275. </div>
276.
277. <div>
278. <label for="price">Price</label>
279. <input data-bind="value: Product().Price" type="text" title="Price" />
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 11/17
6/27/2014 Web API CRUD Operations with Knockout
280.
281. </div>
282. <br />
283. <div>
284. <button data-bind="click: $root.update">Update</button>
285. <button data-bind="click: $root.cancel">Cancel</button>
286.
287. </div>
288. </div>
289.
290. <div data-bind="ifnot: Product()">
291. <div>
292. <h2>Add New Product</h2>
293. </div>
294. <div>
295. <label for="name">Name</label>
296. <input data-bind="value: $root.Name" type="text" title="Name" />
297. </div>
298.
299. <div>
300. <label for="category">Category</label>
301. <input data-bind="value: $root.Category" type="text" title="Category" />
302. </div>
303.
304. <div>
305. <label for="price">Price</label>
306. <input data-bind="value: $root.Price" type="text" title="Price" />
307. </div>
308. <br />
309. <div>
310. <button data-bind="click: $root.create">Save</button>
311. <button data-bind="click: $root.reset">Reset</button>
312.
313. </div>
314. </div>
315.
316. </div>
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 12/17
6/27/2014 Web API CRUD Operations with Knockout
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 13/17
6/27/2014 Web API CRUD Operations with Knockout
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 14/17
6/27/2014 Web API CRUD Operations with Knockout
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 15/17
6/27/2014 Web API CRUD Operations with Knockout
Print Article
Tw eet
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 16/17
6/27/2014 Web API CRUD Operations with Knockout
Shailendra Chauhan works as Software Analyst at reputed MNC and has more than 5 years of hand
over Microsoft .NET technologies. He is a .NET Consultant and is the founder & chief editor of
www.dotnet-tricks.com and www.dotnetinterviewtricks.com blogs. He is an author of book ASP.NET
MVC Interview Questions and Answers.
He loves to work with web applications and mobile apps using Microsoft technology including ASP.NET,
MVC, C#, SQL Server, WCF, Web API, Entity Framework,Cloud Computing, Windows Azure, jQuery,
jQuery Mobile, Knockout.js, Angular.js and many more web technologies. More...
http://www.dotnet-tricks.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.html 17/17