Вы находитесь на странице: 1из 17

6/27/2014 Web API CRUD Operations with Knockout

Web API CRUD Operations with Knockout


P o st e d By : S h aile ndra Ch auh an, 0 1 Apr 2 0 1 3
U pdat e d On : 0 1 Apr 2 0 1 3
Ke y wo rd s : CRU D o p e ra t i o n s u s i n g k n o ck o u t a n d we b a p i ,i n s e rt u p d a t e d e l e t e u s i n g
k n o ck o u t a n d we b a p i ,we b a p i i n s e rt u p d a t e d e l e t e

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.

Step 1: Define Model

Product.cs

1. public class Product


2. {
3. public int Id { get; set; }
4. public string Name { get; set; }
5. public string Category { get; set; }
6. public decimal Price { get; set; }
7. }

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

1. public class ProductRepository : IProductRepository


2. {
3. private List<Product> products = new List<Product>();
4. private int _nextId = 1;
5.
6. public ProductRepository()
7. {
8. // Add products for the Demonstration

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

9. Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M


});
10. Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M
});
11. Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });
12. }
13.
14. public IEnumerable<Product> GetAll()
15. {
16. // TO DO : Code to get the list of all the records in database
17. return products;
18.
19. }
20.
21. public Product Get(int id)
22. {
23. // TO DO : Code to find a record in database
24. return products.Find(p => p.Id == id);
25.
26. }
27.
28. public Product Add(Product item)
29. {
30. if (item == null)
31. {
32. throw new ArgumentNullException("item");
33. }
34.
35. // TO DO : Code to save record into database
36. item.Id = _nextId++;
37. products.Add(item);
38.
39. return item;
40. }
41. public bool Update(Product item)
42. {
43. if (item == null)
44. {
45. throw new ArgumentNullException("item");
46. }

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. }

Step 2: Define Controller

HomeController.cs

1. public class HomeController : Controller


2. {
3. public ActionResult Product()
4. {
5. return View();
6. }
7. }

ProductController.cs for Web API

1. public class ProductController : ApiController


2. {
3. static readonly IProductRepository repository = new ProductRepository();
4.
5. public IEnumerable GetAllProducts()
6. {

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. }

Step 3: Define View

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

121. type: 'POST',


122. contentType: 'application/json; charset=utf-8',
123. data: ko.toJSON(Product),
124. success: function (data) {
125. // alert('added');
126. self.Products.push(data);
127. self.Name("");
128. self.Price("");
129. self.Category("");
130.
131. }
132. }).fail(
133. function (xhr, textStatus, err) {
134. alert(err);
135. });
136.
137. }
138. else {
139. alert('Please Enter All the Values !!');
140. }
141.
142. }
143. // Delete product details
144. self.delete = function (Product) {
145. if (confirm('Are you sure to Delete "' + Product.Name + '" product ??')) {
146. var id = Product.Id;
147. $.ajax({
148. url: 'api/product/' + id,
149. cache: false,
150. type: 'DELETE',
151. contentType: 'application/json; charset=utf-8',
152. data: {},
153. success: function (data) {
154. self.Products.remove(Product);
155.
156. }
157. }).fail(
158. function (xhr, textStatus, err) {
159. alert(err);
160. });

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>

Step 4: Run Application - Retrieve Operation

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

Step 4: Insert Operation

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

Step 4: Update Operation

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

Step 4: Delete Operation

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

What do you think?


I hope you will enjoy the tips while working with Knockout and Web API. I would like to have feedback
from my blog readers. Your valuable feedback, question, or comments about this article are always
welcome.
Download Code

Print Article

Share this article with your friends!


in S h a r e 1 9

Tw eet

About the Author

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