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

return products. Price = 23. 18. } 41. Add(new Product { Name = "Computer". 12. 26. 35. Category = "Electronics".6/27/2014 Web API CRUD Operations with Knockout 9. if (item == null) 31. { 23. } 13. } 34. return item.html 2/17 . 38. throw new ArgumentNullException("item"). { 45. } 20. public IEnumerable<Product> GetAll() 15. if (item == null) 44. Add(new Product { Name = "Laptop". Category = "Phone". 19. Add(new Product { Name = "iPhone4". 14. // TO DO : Code to save record into database 36. // TO DO : Code to find a record in database 24. item. } 27. public Product Add(Product item) 29.99M }).com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. 10. 25. throw new ArgumentNullException("item").Id == id). { 16. { 32. Category = "Electronics".54M }). 21. 33.Id = _nextId++. } http://www. Price = 16. 39. public bool Update(Product item) 42. 46. public Product Get(int id) 22. // TO DO : Code to get the list of all the records in database 17.75M }). { 43.dotnet-tricks.Find(p => p. return products. 11.Add(item). 28. products. 37. Price = 33. { 30. 40.

} 67. 58. 56. public class HomeController : Controller 2. 64. // TO DO : Code to update record into database 49. { http://www. 50. public bool Delete(int id) 61. // TO DO : Code to remove the records from database 63.cs for Web API 1. { 3. 6. static readonly IProductRepository repository = new ProductRepository().Insert(index. { 52.dotnet-tricks. return View().RemoveAll(p => p. public ActionResult Product() 4.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. } 54. 65. { 5. 55. 57. } ProductController.Id == id). 66. 53.Id == item. if (index == -1) 51. 5. public class ProductController : ApiController 2. products. 48.RemoveAt(index). products.6/27/2014 Web API CRUD Operations with Knockout 47. return true. } 59.item). 60. } Step 2: Define Controller HomeController. { 62. return true.html 3/17 . } 7. int index = products. 4. public IEnumerable GetAllProducts() 6.cs 1.FindIndex(p => p. { 3. return false.Id). products.

@{ 2. } 9. if (repository. { 20. product. { 36. return repository. public bool DeleteProduct(int id) 29. if (repository. } 34. } Step 3: Define View Product.Delete(id)) 31. 8. return false. 28.Update(product)) 19. } 40. return null.Id = id.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. 13. 37. public Product PostProduct(Product item) 11. 18. Product product) 16. 25. { 32. 10.Title = "Products' List". 33. } 22. return true.dotnet-tricks. { 30. { 17.GetAll(). { 24. { 12. else 35. http://www.GetAll(). return repository.html 4/17 . } 14. return repository. } 38. } 27.Add(item). 21. else 23.6/27/2014 Web API CRUD Operations with Knockout 7.cshtml 1. public IEnumerable PutProduct(int id. 39. 15. } 26. ViewBag.

background: #282828.4em.html 5/17 . display: inline-block. display: inline-block. 25. sans-serif. 14. 41. 23. background: #1276bb. cursor: pointer. 9. 5. 31. 29. 17. label { 13. 15. padding-top: 1em. 21. @section scripts { 6.1em . border: solid 1px #000. thead. } 38.4em 1. text-align: center. } 28. button:hover { 30. margin: 20px. 27. } 34. http://www. 37. 24. button { 18. 26. 39.6/27/2014 Web API CRUD Operations with Knockout 3. "Helventica". 22. 10. padding: . 12. color: #fef4e9. } 11. text-decoration: none. text-decoration: none. 33. <style type="text/css"> 7. 32. } 4. 20. table { 36. font-family: "Arial". } 42. body { 8. width: 80px. outline: none. font-weight: 600. 35.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.dotnet-tricks. border: solid 1px #006fb9. tfoot { 40. } 16. 19.

Category = ko. } 47. <script src="~/Scripts/knockout-2. } 52.0. td { 44. 46. } 60. 53.Name = ko. 45. 63. 79. return "$" + value. 75. <script src="@Url. padding: 0.html 6/17 . function ProductViewModel() { 74.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. //Make the self as 'this' reference 76. td li:last-child::after { 62. <script type="text/javascript"> 68.observable(""). text-align: left. td li.Content("~/Scripts/knockout-2. </style> 65. function formatCurrency(value) { 70. content: '. 59. } 64. padding: .observable(""). self. } 56.js")" type="text/javascript"></script> 67. 77. th.observable(""). 48.Id = ko.5em. self.1em .js"></script> 66. content: ''. 61. td li::after { 58. 50. self.dotnet-tricks.observable("").0. 55. 57. self. td ul { 49. margin: 0. 80.debug. //Declare observable which will be bind with UI 78. 69. display: inline. td li { 54. 51. var self = this. http://www. 81. } 72. 73.toFixed(2). 71.'.2.2.6/27/2014 Web API CRUD Operations with Knockout 43.Price = ko.

6/27/2014 Web API CRUD Operations with Knockout 82.observable(). Category: self. var sum = 0. cache: false. var Product = { 84. // Contains the list of products 92. }). success: function (data) { 101. 114. self.create = function () { 117. data: {}. 105. 85.Products(). 87. charset=utf-8'. $.Price.computed(function () { 107. 111. 115.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. url: 'api/product'.length. 104.Product = ko. // Calculate Total of Price After Initialization 106. return sum. for (var i = 0. }.ajax({ 119.Category 88. 97. 83.Price. 120.Id.Total = ko. i++) { 110. 93. 109. type: 'GET'. Name: self. 108.dotnet-tricks. 96. sum += arr[i]. //Put the response in ObservableArray 102. var arr = self.Name() != "" && Product. url: 'api/product'. i < arr. http://www.Category() != "") { 118. // Initialize the view-model 94. 99. 91. 90. self. 89. $. self. 113.Price() != "" && Product. } 112. cache: false. } 103. //Add New Item 116. if (Product. self.Products = ko. self.html 7/17 . 98.observableArray(). Price: self.ajax({ 95. 100. }). 86. contentType: 'application/json. Id: self.Name.Products(data).

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

//Put the response in ObservableArray 184. self. 185. 187. } 188. $. 181.dotnet-tricks. 175.edit = function (Product) { 166. 193.Category(""). self. contentType: 'application/json. 164. 199.reset = function () { 197. } 162. }). .html 9/17 .fail( 190.Price(""). // Update product details 171. data: ko. 174. 170. var Product = self. 192. success: function (data) { 182.Name("").Id. charset=utf-8'. self. 177. 183. alert("Record Updated Successfully"). err) { 191. var id = Product. function (xhr. } 163. self. type: 'PUT'. self. self.ajax({ 176. self. } 169. 173. alert(err). // Edit product details 165. cache: false.Product(). // Reset product details 196.toJSON(Product).Products(data). textStatus.Products. } 194. 178. }) 189. 168. self. url: 'api/product/' + id.Product(Product). } http://www.removeAll(). 200. 179. 195. 167.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. self. self. 186.update = function () { 172. 198.Product(null). 180.6/27/2014 Web API CRUD Operations with Knockout 161.

dotnet-tricks. <button data-bind="click: $root.cancel = function () { 204. 209. <tbody data-bind="foreach: Products"> 231. <tr> 232. 218. <th>Price</th> 227. <td> 238. <th>Category</th> 226.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. <td data-bind="text: Category"></td> 235. 211. <button data-bind="click: $root. 237. } 208.applyBindings(viewModel). 220. </thead> 230.delete">Delete</button> 240.edit">Edit</button> 239. <th>Name</th> 225. <td data-bind="text: Name"></td> 234.6/27/2014 Web API CRUD Operations with Knockout 201. 206. <h2>Knockout CRUD Operations with MVC4</h2> 217. self. } 213. ko. // Cancel product details 203. 214. 205. <table id="products1" data-bind="visible: Products(). var viewModel = new ProductViewModel(). 216.html 10/17 . 202. <th>Actions</th> 228. 210. http://www. <td data-bind="text: Id"></td> 233.length > 0"> 221. <th>ID</th> 224.Product(null). <h3>List of Products</h3> 219. <td data-bind="text: formatCurrency(Price)"></td> 236. <thead> 222. <tr> 223. </tr> 229. <div id="body"> 215. self. </script> 212. } 207.

</table> 255. <tfoot> 246. <div> 278. <td></td> 248.html 11/17 . <td></td> 252. <label for="name">Name</label> 269. <label for="productId" data-bind="visible: false">ID</label> 264. <div> 260. <div style="border-top: solid 2px #282828. <td data-bind="text: formatCurrency($root. 277. width: 430px. 272. </div> 262. <input data-bind="value: Product(). </tr> 253. <div data-bind="if: Product"> 259. </div> 267. </tfoot> 254.Total())"></td> 251. <td></td> 249. 243. </div> 276. <div> 268. 266. </tr> 244. visible: false"></label> 265. <td>Total :</td> 250. <h2>Update Product</h2> 261. <tr> 247. <label for="category">Category</label> 274.dotnet-tricks. <label for="price">Price</label> 279. <div> 263. <input data-bind="value: Product(). <div> 273. </div> 271. <input data-bind="value: Product().6/27/2014 Web API CRUD Operations with Knockout 241. height: 10px"> </div> 257. <label data-bind="text: Product(). 258. </tbody> 245. </td> 242.Category" type="text" title="Category" /> 275.Name" type="text" title="Name" /> 270. <br /> 256.Price" type="text" title="Price" /> http://www.Id.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.

281. <div data-bind="ifnot: Product()"> 291. </div> 289. 299. 290.create">Save</button> 311. </div> 314.reset">Reset</button> 312. 304. </div> 315. 287. </div> 288.Price" type="text" title="Price" /> 307. <div> 284. <input data-bind="value: $root. </div> Step 4: Run Application . <label for="price">Price</label> 306. </div> 282.Category" type="text" title="Category" /> 302.html 12/17 . <div> 295. <label for="category">Category</label> 301.dotnet-tricks. <div> 300. <input data-bind="value: $root. <button data-bind="click: $root. <label for="name">Name</label> 296. <div> 310. <input data-bind="value: $root.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. 316.update">Update</button> 285. <button data-bind="click: $root. </div> 298. <button data-bind="click: $root. <div> 305. <br /> 309.6/27/2014 Web API CRUD Operations with Knockout 280. </div> 294. 313. <h2>Add New Product</h2> 293. </div> 303. <br /> 283.Retrieve Operation http://www.cancel">Cancel</button> 286. <div> 292.Name" type="text" title="Name" /> 297. <button data-bind="click: $root. </div> 308.

html 13/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.

6/27/2014 Web API CRUD Operations with Knockout Step 4: Update Operation http://www.dotnet-tricks.html 14/17 .com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.

dotnet-tricks.6/27/2014 Web API CRUD Operations with Knockout Step 4: Delete Operation http://www.html 15/17 .com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout.

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. or comments about this article are always welcome.html 16/17 . Your valuable feedback.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. I would like to have feedback from my blog readers. question.dotnet-tricks. 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. SQL Server.com and www.. He is a .NET Consultant and is the founder & chief editor of www.NET MVC Interview Questions and Answers.html 17/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 .dotnet-tricks. Entity Framework. Knockout. MVC.com/Tutorial/knockout/8L0T010413-Web-API-CRUD-Operations-with-Knockout. Angular. WCF. jQuery. More. He loves to work with web applications and mobile apps using Microsoft technology including ASP.NET technologies.NET..dotnetinterviewtricks. Windows Azure.com blogs. http://www.Cloud Computing. Web API. jQuery Mobile. He is an author of book ASP.js. C#.js and many more web technologies.