Create Read/Write Web API and Cunsume It By HTML Client

Introduction

In this article, I will create a Read/Write API and consume it by a HTML client. In the previous article we created a Read Only API "Create Read Only Web API". Now we will perform some changes in the previous article for creating the Read/Write.

Open the "ReadOnly" Web API application.

Step 1

In the "SimpleRepository.cs" file we add the data persistence features that allows the application for accepting the user input and a new instance.

Repository Class

  • Open the "SimpleRepository.cs" file from the "Services" folder and add the key name of cache item to this file.
    1. private const string CacheKey = "SimpleStore";
  • Now we add the Constructor in this repository class:
    1. public SimpleRepository()  
    2. {  
    3.     var smp = HttpContext.Current;  
    4.     if (smp != null)  
    5.     {  
    6.         if (smp.Cache[CacheKey] == null)  
    7.         {  
    8.             var simples = new Simple[]  
    9.             {  
    10.                 new Simple  
    11.                 {  
    12.                     ID=1,  
    13.                     Name="Smith Patel"  
    14.                 },  
    15.                 new Simple  
    16.                 {  
    17.                     ID=2,  
    18.                     Name="Virat Kohli"  
    19.                 },  
    20.                 new Simple  
    21.                 {  
    22.                     ID=3,  
    23.                     Name="Rohit Shrma"  
    24.               }  
    25.             };  
    26.             smp.Cache[CacheKey] = simples;  
    27.         }  
    28.     }  
    29. }  
  • Now we must modife the "GetAllSimples()" method in the Repository class. The modified code is that:
    1. public Simple[] GetAllSimples()  
    2. {  
    3.     var smp = HttpContext.Current;  
    4.     if (smp != null)  
    5.     {  
    6.         return (Simple[])smp.Cache[CacheKey];  
    7.     }  
    8.     return new Simple[]  
    9.     {  
    10.         new Simple  
    11.         {  
    12.             ID = 0,  
    13.             Name = "Placeholder"  
    14.         }  
    15.     };  
    16. }
    The main purpose of this example is to use the web server as the storage medium. This provides the values for the multiple clients simultaneously. And we can use it as a storage medium or Request a storage medium.
  • Now we will add the new method "SaveSimple" for saving the new record. It will take a single parameter at a time and return a Boolean value, it is saved or not.
    1. public bool SaveSimple(Simple contact)  
    2. {  
    3.     var smp = HttpContext.Current;  
    4.     if (smp != null)  
    5.     {  
    6.         try  
    7.         {  
    8.             var currentData = ((Simple[])smp.Cache[CacheKey]).ToList();  
    9.             currentData.Add(contact);  
    10.             smp.Cache[CacheKey] = currentData.ToArray();  
    11.             return true;  
    12.         }  
    13.         catch (Exception ex)  
    14.         {  
    15.             Console.WriteLine(ex.ToString());  
    16.             return false;  
    17.         }  
    18.     }  
    19.     return false;  
    20.  

Step 2

Now we consume the Web API by the HTML client. So we need to make some change in the "index.cshtml" file. Open the "index.cshtml" file and add the new code to the file.

  • In the Solution Explorer.
  • Select the Views/Home and open the "index.cshtml" file.

Index file

Replace this HTML code in the body tag:

  1. <div id="body">  
  2.     <ul id="simples"></ul>  
  3. </div> 

Now add this JavaScript code at the end of the <div> closing tag:

  1. @section scripts{  
  2.     <script type="text/javascript">  
  3.         $(function () {  
  4.             $.getJSON('/api/simple'function (contactsJsonPayload) {  
  5.                 $(contactsJsonPayload).each(function (i, item) {  
  6.                     $('#simples').append('<li>' + item.Name + '</li>');  
  7.                 });  
  8.             });  
  9.         });  
  10.     </script>  
  11. } 

Step 3

Now execute the application, we can see that all the records are called by the Web API and displayed on the browser:

Show all Name

Step 4

Now we need to change the View  of the "index.cshtml" file for creating the new records. We modify the index view, add the HTML page for catching the input of the user and send it to the Web API for adding the new record. And in the "SimpleController.cs" class add a new Method POST for adding a new record.

First open the SimpleController class and add the POST method:

  • In the Solution Explorer.
  • Select the Controller folder and open the SimpleController.cs.
  • Add the following code:

Simple Controller

  1. public HttpResponseMessage Post(Simple simple)  
  2. {  
  3.     this.simplerepository.SaveSimple(simple);  
  4.     var response = Request.CreateResponse<Simple>(System.Net.HttpStatusCode.Created, simple);  
  5.     return response;  
  6. } 

Step 5

Now again modify the index.cshtml file.

We will add the following HTML code at the bottom of the creating the unordered list.

  1. <form id="saveSimpleForm" method="post">  
  2.     <h3>Create a new Simple</h3>  
  3.     <p>  
  4.         <label for="simpleId">Simple Id:</label>  
  5.         <input type="text" name="ID" />  
  6.     </p>  
  7.     <p>  
  8.         <label for="simpleName">Simple Name:</label>  
  9.         <input type="text" name="Name" />  
  10.     </p>  
  11.     <input type="button" id="saveSimple" value="Save" />  
  12. </form> 

Now we will add the following scripting code within the Script tag.

  1. $('#saveSimple').click(function()  
  2. {  
  3.      $.post("api/simple",  
  4.            $("#saveSimpleForm").serialize(),  
  5.            function(value)  
  6.            {  
  7.                 $('#simples').append('<li>' + value.Name + '</li>');  
  8.            },  
  9.            "json"  
  10.      );  
  11. }); 

Step 6

Insert the breakpoint on the POST method in the SimpleController class. Then execute the application, insert the id and name and click on the "Save" button then we can see that it breaks the POST method and see the property of the simple parameter, we can see the value passed in these parameters.

Post Data Display by Breakpoint

Step 7

Now remove the breakpoint and execute the application again. When we insert the new record and click on the "Save" button, it is stored by the SimpleRepository class.

Post the Data