Using CRUD Operations in ASP.Net Web API

Introduction

In this article I will use the CRUD (Create, Read, Update, Delete) operations in the ASP. NET Web API. These operations are used in databases. These are the basic operations for databases. Here we create a simple list of Items to be managed using these CRUD operations. For using the CRUD operations in ASP. NET Web API use the following procedure.

Step 1

First we create the Web API Project.

  • Start Visual Studio 2012 and select "New Project" from the Start Page.
  • In the Template window, select "Installed template" -> "Visual C#" -> "Web".
  • Choose "ASP. NET MVC 4 Web Application" then change its name.
  • Click on the "OK" button.

    it.jpg

  • MVC 4 Project window:

    it1.jpg

  • Select "Web API" and click on the "OK" button.

Step 2

Create a Model Class and name it "Item.cs".

  • In the "Solution Explorer", right-click on the "Model Folder" then select "Add" -> "Class".

    it2.jpg

  • In  the Template window, select "Installed template" -> "Visual C#".

    it3.jpg

  • Choose "Class". Change its name.
  • Click on the "OK" button.

Now type this code in the "Item.cs" class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace ItemCollection.Models  
  6. {  
  7.     public class Item  
  8.     {  
  9.         public int Id { getset; }  
  10.         public string Name { getset; }  
  11.         public string Category { getset; }  
  12.         public decimal Price { getset; }  
  13.     }  
  14. } 

Step 3

Create an "Interface" and name it "ItemRepository".

  • In the "Solution Explorer" right-click on the "Model folder" then select "Add" -> "New Item".

    it13.jpg

  • In the Template window, select "Installed template" -> "Visual C#".

    it5.jpg

  • Choose "Interface" and change its name.
  • Click on the "OK" button.

Write this code in the "ItemRepository.cs":

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace ItemCollection.Models  
  7. {  
  8.     interface ItemRepository  
  9.     {  
  10.         IEnumerable<Item> GetAll();  
  11.         Item Get(int id);  
  12.         Item Add(Item item);  
  13.         void Remove(int id);  
  14.         bool Update(Item item);  
  15.     }  
  16. } 

Step 4

Create a new Model class name as "IItemRepostory.cs"

  • In the "Solution Explorer" ,Right-click on the "Model Folder"->"Add"->"Class".
  • In the Template window, select "Installed template"->"Visual C#".

    it4.jpg

  • Choose "Class". Change its name.
  • Click on "OK" button.

Write this code in the "IItemRepostory.cs" file.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace ItemCollection.Models  
  6. {  
  7.     public class IItemRepostory:ItemRepository  
  8.     {  
  9.         private List<Item> items = new List<Item>();  
  10.         private int _nextId = 1;  
  11.         public IItemRepostory()  
  12.         {  
  13.             Add(new Item { Name = "Tomato", Category = "Vagitable", Price = 100});  
  14.             Add(new Item { Name = "Apple", Category = "Fruit", Price = 150 });  
  15.             Add(new Item { Name = "Suit", Category = "Cloth", Price = 200});  
  16.         }  
  17.         public IEnumerable<Item> GetAll()  
  18.         {  
  19.             return items;  
  20.         }  
  21.         public Item Get(int id)  
  22.         {  
  23.             return items.Find(p => p.Id == id);  
  24.         }  
  25.         public Item Add(Item item)  
  26.         {  
  27.             if (item == null)  
  28.             {  
  29.                 throw new ArgumentNullException("item");  
  30.             }  
  31.             item.Id = _nextId++;  
  32.             items.Add(item);  
  33.             return item;  
  34.         }  
  35.         public void Remove(int id)  
  36.         {  
  37.             items.RemoveAll(p => p.Id == id);  
  38.         }  
  39.         public bool Update(Item item)  
  40.         {  
  41.             if (item == null)  
  42.             {  
  43.                 throw new ArgumentNullException("item");  
  44.             }  
  45.             int index = items.FindIndex(p => p.Id == item.Id);  
  46.             if (index == -1)  
  47.             {  
  48.                 return false;  
  49.             }  
  50.             items.RemoveAt(index);  
  51.             items.Add(item);  
  52.             return true;  
  53.         }  
  54.     }  
  55. } 

Step 5

Create a Web API Controller Class and name it "ItemsController.cs".

  • In the "Solution Explorer" right-click on the "Controller Folder" then select "Add" -> "Controller".

    it6.jpg

  • In the Add Controller window set the Controller name.

    it7.jpg

  • Select "Template" -> "Empty API controller".
  • Click on the "OK" button.

Write this code in the "ItemsController.cs" class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using ItemCollection.Models;  
  8. namespace ItemCollection.Controllers  
  9. {  
  10.     public class ItemsController : ApiController  
  11.     {  
  12.         static readonly ItemRepository repository = new IItemRepostory();  
  13.         public IEnumerable<Item> GetAllProducts()  
  14.         {  
  15.             return repository.GetAll();  
  16.         }  
  17.         public Item GetProduct(int id)  
  18.         {  
  19.             Item item = repository.Get(id);  
  20.             if (item == null)  
  21.             {  
  22.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  23.             }  
  24.             return item;  
  25.         }  
  26.         public IEnumerable<Item> GetProductsByCategory(string category)  
  27.         {  
  28.             return repository.GetAll().Where(  
  29.                 p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));  
  30.         }  
  31.         public HttpResponseMessage PostProduct(Item item)  
  32.         {  
  33.             item = repository.Add(item);  
  34.             var response = Request.CreateResponse<Item>(HttpStatusCode.Created, item);  
  35.             string uri = Url.Link("DefaultApi"new { id = item.Id });  
  36.             response.Headers.Location = new Uri(uri);  
  37.             return response;  
  38.         }  
  39.         public void PutProduct(int id, Item product)  
  40.         {  
  41.             product.Id = id;  
  42.             if (!repository.Update(product))  
  43.             {  
  44.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  45.             }  
  46.         }  
  47.         public void DeleteProduct(int id)  
  48.         {  
  49.             repository.Remove(id);  
  50.         }  
  51.     }  
  52. } 

Step 6

Open the "Index.cshtml" file.

  • In the "Solution Explorer".
  • Select "Views" -> "Home" -> "Index.cshtml".

    it12.jpg

  • Double-click on the "Index.cshtml" file.

Write this code in the "Index.cshtml" file:

  1. @{  
  2.     ViewBag.Title = "Item Collection";  
  3. }  
  4. @section scripts {  
  5.     <style type="text/css">  
  6.         table  
  7.         {  
  8.             border: 1px solid #000;  
  9.             border-collapse: collapse;  
  10.             color: #666666;  
  11.             min-width: 200px;  
  12.         }  
  13.         tr  
  14.         {  
  15.             border: 1px solid #000;  
  16.             line-height: 25px;  
  17.         }  
  18.         th  
  19.         {  
  20.             background-color: #B1C3CC;  
  21.             color: #000;  
  22.             font-size: 13px;  
  23.             text-align: left;  
  24.         }  
  25.         th, td  
  26.         {  
  27.             padding-left: 5px;  
  28.         }  
  29.         #status {  
  30.             color: red;  
  31.         }  
  32.     </style>  
  33.     <script src="@Url.Content("~/Scripts/knockout-2.1.0.debug.js")" type="text/javascript"></script>  
  34.     <script type="text/javascript">  
  35.         function ViewModel() {  
  36.             var self = this;  
  37.             function ItemViewModel(item) {  
  38.                 var self = this;  
  39.                 self.Id = item.Id;  
  40.                 self.Name = item.Name;  
  41.                 self.Price = item.Price;  
  42.                 self.Category = item.Category;  
  43.             }  
  44.             self.items = ko.observableArray();   
  45.             self.item = ko.observable();  
  46.             self.status = ko.observable();  
  47.             self.getAll = function () {  
  48.                 self.items.removeAll();  
  49.                 $.getJSON("/api/items"function (items) {  
  50.                     $.each(items, function (index, item) {  
  51.                         self.items.push(new ItemViewModel(item));  
  52.                     })  
  53.                 });  
  54.             }  
  55.             self.getById = function () {  
  56.                 self.status("");  
  57.                 var id = $('#itemId').val();  
  58.                 if (!id.length) {  
  59.                     self.status("ID is required");  
  60.                     return;  
  61.                 }  
  62.                 $.getJSON(  
  63.                     'api/items/' + id,  
  64.                     function (data) {  
  65.                         self.item(new ItemViewModel(data));  
  66.                     })  
  67.                         function (xhr, textStatus, err) {  
  68.                             self.item(null);  
  69.                             self.status(err);  
  70.                         });  
  71.             }  
  72.             self.update = function () {  
  73.                 self.status("");  
  74.                 var id = $('#itemId').val();  
  75.                 var item = {  
  76.                     Name: $('#name').val(),  
  77.                     Price: $('#price').val(),  
  78.                     Category: $('#category').val()  
  79.                 };  
  80.                 $.ajax({  
  81.                     url: 'api/items/' + id,  
  82.                     cache: false,  
  83.                     type: 'PUT',  
  84.                     contentType: 'application/json; charset=utf-8',  
  85.                     data: JSON.stringify(item),  
  86.                     success: self.getAll  
  87.                 })  
  88.                 .fail(  
  89.                 function (xhr, textStatus, err) {  
  90.                     self.status(err);  
  91.                 });  
  92.             }  
  93.             self.create = function () {  
  94.                 self.status("");  
  95.                 var item = {  
  96.                     Name: $('#name2').val(),  
  97.                     Price: $('#price2').val(),  
  98.                     Category: $('#category2').val()  
  99.                 };  
  100.                 $.ajax({  
  101.                     url: 'api/items',  
  102.                     cache: false,  
  103.                     type: 'POST',  
  104.                     contentType: 'application/json; charset=utf-8',  
  105.                     data: JSON.stringify(item),  
  106.                     statusCode: {  
  107.                         201 : function (data) {  
  108.                             self.items.push(data);  
  109.                         }  
  110.                     }  
  111.                 })  
  112.                 .fail(  
  113.                 function (xhr, textStatus, err) {  
  114.                     self.status(err);  
  115.                 });  
  116.             }  
  117.                      $.getJSON("/api/items"function (items) {  
  118.                 $.each(items, function (index, item) {  
  119.                     self.items.push(new ItemViewModel(item));  
  120.                 })  
  121.             });  
  122.         }  
  123.         function clearStatus() {  
  124.             $('#status').html('');  
  125.         }  
  126.         function add() {  
  127.             clearStatus();  
  128.             var item = ko.toJS(viewModel);  
  129.             var json = JSON.stringify(item);  
  130.             $.ajax({  
  131.                 url: API_URL,  
  132.                 cache: false,  
  133.                 type: 'POST',  
  134.                 contentType: 'application/json; charset=utf-8',  
  135.                 data: json,  
  136.                 statusCode: {  
  137.                     201 : function (data) {  
  138.                         self.items.push(data);  
  139.                     }  
  140.                 }  
  141.             });  
  142.         }  
  143.         var viewModel = new ViewModel();  
  144.         ko.applyBindings(viewModel);  
  145.         $("#tabs").tabs();  
  146.     </script>  
  147. }  
  148. <div id="body">  
  149.     <section class="content-wrapper main-content">  
  150.         <h3>Items</h3>  
  151.         <table id="items">  
  152.         <thead>  
  153.             <tr><th>ID</th><th>Name</th><th>Category</th><th>Price</th></tr>  
  154.         </thead>  
  155.         <tbody data-bind="foreach: items">  
  156.             <tr>  
  157.                 <td data-bind="text: Id"></td>  
  158.                 <td data-bind="text: Name"></td>  
  159.                 <td data-bind="text: Category"></td>  
  160.                 <td data-bind="text: Price"></td>  
  161.             </tr>  
  162.         </tbody>  
  163.         </table>  
  164.     </section>  
  165.     <section id="detail" class="content-wrapper">  
  166.     <div id="tabs">  
  167.            <ul>  
  168.                   <li><a href="#viewTab">View Item</a></li>  
  169.                   <li><a href="#addNewTab">Add New Item</a></li>  
  170.            </ul>  
  171.         <div id="viewTab">  
  172.         <label for="itemId">ID</label>  
  173.         <input type="text" title="ID" name='Id' id="itemId" size="5"/>  
  174.         <input type="button" value="Get" data-bind="click: getById"/>  
  175.         <div data-bind="if: item()">  
  176.             <div>  
  177.             <label for="name">Name</label>  
  178.             <input data-bind="value: item().Name" type="text" title="Name" id="name" />  
  179.             </div>  
  180.             <div>  
  181.             <label for="category">Category</label>  
  182.             <input data-bind="value: item().Category" type="text" title="Category" id="category" />  
  183.             </div>  
  184.             <div>  
  185.             <label for="price">Price</label>  
  186.             <input data-bind="value: item().Price" type="text" title="Price" id="price" />  
  187.             </div>  
  188.             <div>  
  189.             <input type="button" value="Update" data-bind="click: update" />  
  190.             </div>  
  191.         </div>  
  192.         </div>  
  193.         <div id="addNewTab">  
  194.             <div>  
  195.             <label for="name">Name</label>  
  196.             <input type="text" title="Name" id="name2" />  
  197.             </div>  
  198.             <div>  
  199.             <label for="category">Category</label>  
  200.             <input type="text" title="Category" id="category2" />  
  201.             </div>  
  202.             <div>  
  203.             <label for="price">Price</label>  
  204.             <input type="text" title="Price" id="price2" />  
  205.             </div>  
  206.             <div>  
  207.             <input type="button" value="Add New" data-bind="click: create"" />  
  208.             </div>  
  209.         </div>  
  210.     </div>  
  211.     <div>  
  212.         <p id="status" data-bind="text: status" />  
  213.     </div>  
  214.     </section>  
  215. </div> 

Step 7

  • Now to execute the application press F5.

    it8.jpg

  • For finding the Item click on "View Tab" and Type the "Id". Then click on the "GET" button.

    it9.jpg

  • Update the Item; change the Name or Category or Price then click on the "Update" button.

    it10.jpg

  • Add a new Item. Type the Name, Category and price of the item and click on the "Add New" button.

    it11.jpg


Similar Articles