ASP.NET Web API Using MVC, Entity Framework And HttpClient For Get And Post With Validation - Part Six

Introduction
 
WEB API is the best fit to create a resource-oriented service using HTTP/Restful and it works well with MVC-based applications. For more details visit my link.
Description
 
In this session, I will show you how to insert records using AA Web API using HttpClient to post data in SQL Server. In this session, you can see get and post operations by Web API. In another way, I can say we'll insert and retrieve records using button click event.
 
Before going through this session, visit my previous session.
Steps to be followed,
 
Step 1
 
Add a new Action to the HomeController (in MVC Client application) for get view for Get data using HTTP Client.
 
Code Ref
  1. public ActionResult Part4()   
  2.         {  
  3.             List<Employee> list = new List<Employee>();  
  4.             HttpClient client = new HttpClient();  
  5.             var result = client.GetAsync("http://localhost:47250/api/satya").Result;  
  6.             if (result.IsSuccessStatusCode)  
  7.             {  
  8.                 list = result.Content.ReadAsAsync<List<Employee>>().Result;  
  9.                 ViewBag.userdetails = list;  
  10.             }  
  11.             return View();  
  12.         } 
Code Description

During page initial load table data will be shown that means the data will bind in table with input controls uisng HttpClient. This controller action method with [HttpGet].
 
Step 2
 
Using same Action to the HomeController (in MVC Client application) for Post data using HTTP Client.
 
Code Ref
  1. [HttpPost]  
  2.     public ActionResult Part4(Employee emp)   
  3.     {  
  4.         if (ModelState.IsValid)  
  5.         {  
  6.             HttpClient client = new HttpClient();  
  7.             var result = client.PostAsJsonAsync("http://localhost:47250/api/satya", emp).Result;  
  8.             if (result.IsSuccessStatusCode)  
  9.             {  
  10.                 emp = result.Content.ReadAsAsync<Employee>().Result;  
  11.                 ViewBag.Result = "Data Is Successfully Saved!";  
  12.                 List<Employee> list = new List<Employee>();  
  13.                 HttpClient client1 = new HttpClient();  
  14.                 var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;  
  15.                 if (result1.IsSuccessStatusCode)  
  16.                 {  
  17.                     list = result1.Content.ReadAsAsync<List<Employee>>().Result;  
  18.                     ViewBag.userdetails = list;  
  19.                 }  
  20.                 ModelState.Clear();  
  21.                 return View(new Employee());  
  22.             }  
  23.             else  
  24.             {  
  25.                 ViewBag.Result = "Error! Please try with valid data.";  
  26.             }  
  27.         }  
  28.         return View(emp);  
  29.     } 
Code Description
 
In this part after form post method or button click event, data insert and tables data wil be shown. In side post section I added soemthing for data retrieval otherwise you'll get an error about Object reference not being set to an instance of an object. I will describe this issue in view section under Note.
  1. List<Employee> list = new List<Employee>();  
  2.                     HttpClient client1 = new HttpClient();  
  3.                     var result1 = client1.GetAsync("http://localhost:47250/api/satya").Result;  
  4.                     if (result1.IsSuccessStatusCode)  
  5.                     {  
  6.                         list = result1.Content.ReadAsAsync<List<Employee>>().Result;  
  7.                         ViewBag.userdetails = list;  
  8.                     } 
Model state dictionary object that contains state of the model and of model binding validation, removes all items from model state dictionary.
  1. ModelState.Clear(); 
Step 3
 
Right Click on Action Method (here right click on form Part4()) > Add View... > Check "Create strongly typed view" > Select Model class >> Add. Here Model Class is "Employee (Entities)".
 
Code Ref
  1. @model Entities.Employee  
  2.   
  3. @{  
  4.     ViewBag.Title = "Satyaprakash - Post data to Web API using HTTPClient (in MVC client application) With Validation";  
  5. }  
  6.   
  7. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  8. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  9. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  10.   
  11.   
  12. <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">  
  13.   
  14. </script>  
  15.   
  16. <style>  
  17.     span.field-validation-error {  
  18.         color: red;  
  19.     }  
  20.   
  21.     table {  
  22.         font-family: arial, sans-serif;  
  23.         border-collapse: collapse;  
  24.         width: 100%;  
  25.     }  
  26.   
  27.     td, th {  
  28.         border: 1px solid #dddddd;  
  29.         text-align: left;  
  30.         padding: 8px;  
  31.     }  
  32.   
  33.     tr:nth-child(even) {  
  34.         background-color: #dddddd;  
  35.     }  
  36.   
  37.     .button {  
  38.         background-color: #4CAF50;  
  39.         border: none;  
  40.         color: white;  
  41.         padding: 15px 32px;  
  42.         text-align: center;  
  43.         text-decoration: none;  
  44.         display: inline-block;  
  45.         font-size: 16px;  
  46.         margin: 4px 2px;  
  47.         cursor: pointer;  
  48.     }  
  49.   
  50.     .button4 {  
  51.         border-radius: 9px;  
  52.     }  
  53. </style>  
  54.   
  55.   
  56. <div style="padding:10px ; align-content:center">  
  57.     <fieldset>  
  58.         <legend style="font-family:Arial Black;color:blue">Post data to Web API using HTTPClient (in MVC client application) With Validation</legend>  
  59.     </fieldset>  
  60. </div>  
  61.   
  62.   
  63. <div style="max-width:600px;">  
  64.     @using (Html.BeginForm("Part4""Home", FormMethod.Post, new { role = "form" }))  
  65.     {  
  66.         @Html.ValidationSummary(true)  
  67.   
  68.         <div class="form-group">  
  69.             @Html.LabelFor(a => a.FirstName)  
  70.             @Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })  
  71.             @Html.ValidationMessageFor(a => a.FirstName)  
  72.         </div>  
  73.         <div class="form-group">  
  74.             @Html.LabelFor(a => a.LastName)  
  75.             @Html.TextBoxFor(a => a.LastName, new { @class = "form-control" })  
  76.             @Html.ValidationMessageFor(a => a.LastName)  
  77.         </div>  
  78.         <div class="form-group">  
  79.             @Html.LabelFor(a => a.EmailID)  
  80.             @Html.TextBoxFor(a => a.EmailID, new { @class = "form-control" })  
  81.             @Html.ValidationMessageFor(a => a.EmailID)  
  82.         </div>  
  83.         <div class="form-group">  
  84.             @Html.LabelFor(a => a.City)  
  85.             @Html.TextBoxFor(a => a.City, new { @class = "form-control" })  
  86.             @Html.ValidationMessageFor(a => a.City)  
  87.         </div>  
  88.         <div class="form-group">  
  89.             @Html.LabelFor(a => a.Country)  
  90.             @Html.TextBoxFor(a => a.Country, new { @class = "form-control" })  
  91.             @Html.ValidationMessageFor(a => a.Country)  
  92.         </div>  
  93.         <input id="btn" type="submit" value="Create" class="button button4" />  
  94.   
  95.         <div style="width:90%; padding:10px; margin:0 auto;">  
  96.             @if (ViewBag.Result != null)  
  97.             {  
  98.                 @*<div style="color:red">@ViewBag.Result</div>*@  
  99.   
  100.                 <script>  
  101.                     $(document).ready(function () {  
  102.                         $('#btn').click(function () {  
  103.                             $('#tableshow').hide();  
  104.                         });  
  105.   
  106.                         bootbox.alert('@ViewBag.Result');  
  107.                         $('#tableshow').show();  
  108.                     });  
  109.                 </script>  
  110.             }  
  111.         </div>  
  112.     }  
  113. </div>  
  114.   
  115. @*System.NullReferenceException , Object reference not set to an instance of an object. This error due to without added for data retrieve comment line code in Part4() in homecontroller in webapplication*@  
  116. <div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">  
  117.     <table class="table table-responsive table-striped table-bordered">  
  118.         <thead>  
  119.             <tr>  
  120.                 <th style="background-color: Yellow;color: blue">Full Name</th>  
  121.                 <th style="background-color: Yellow;color: blue">Email</th>  
  122.                 <th style="background-color: Yellow;color: blue">City</th>  
  123.                 <th style="background-color: Yellow;color: blue">Country</th>  
  124.             </tr>  
  125.         </thead>  
  126.         <tbody>  
  127.             @foreach (var i in ViewBag.userdetails)   
  128.             {  
  129.                 <tr>  
  130.                     <td>@i.FirstName @i.LastName</td>  
  131.                     <td>@i.EmailID</td>  
  132.                     <td>@i.City</td>  
  133.                     <td>@i.Country</td>  
  134.                 </tr>  
  135.             }  
  136.         </tbody>  
  137.     </table>  
  138. </div>  
  139. @*System.NullReferenceException , Object reference not set to an instance of an object.*@  
  140.   
  141. @section Scripts{  
  142.     @Scripts.Render("~/bundles/jqueryval")  

Code Description
 
In this code section inside form post method added a script so that during button click event table data will be shown.
  1. <div style="width:90%; padding:10px; margin:0 auto;">  
  2.             @if (ViewBag.Result != null)  
  3.             {  
  4.                 @*<div style="color:red">@ViewBag.Result</div>*@  
  5.   
  6.                 <script>  
  7.                     $(document).ready(function () {  
  8.                         $('#btn').click(function () {  
  9.                             $('#tableshow').hide();  
  10.                         });  
  11.   
  12.                         bootbox.alert('@ViewBag.Result');  
  13.                         $('#tableshow').show();  
  14.                     });  
  15.                 </script>  
  16.             }  
  17.         </div> 
Here I used bootbox library to show alert notification. ViewBag.Result contains message in controller action method.
  1. bootbox.alert('@ViewBag.Result'); 
Note 
During this session I was facing an issue about System.NullReferenceException, Object reference is not set to an instance of an object.
 
So, iIcreated a div id and put it inside script section as described in post method of Part4() controller action method. This error was due to lack of added data for data retrieval comment line code in Part4() in homecontroller in MVC client application.
  1. <div id="tableshow" style="width:90%; padding:10px; margin:0 auto;">  
  2.     <table class="table table-responsive table-striped table-bordered">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th style="background-color: Yellow;color: blue">Full Name</th>  
  6.                 <th style="background-color: Yellow;color: blue">Email</th>  
  7.                 <th style="background-color: Yellow;color: blue">City</th>  
  8.                 <th style="background-color: Yellow;color: blue">Country</th>  
  9.             </tr>  
  10.         </thead>  
  11.         <tbody>  
  12.             @foreach (var i in ViewBag.userdetails)   
  13.             {  
  14.                 <tr>  
  15.                     <td>@i.FirstName @i.LastName</td>  
  16.                     <td>@i.EmailID</td>  
  17.                     <td>@i.City</td>  
  18.                     <td>@i.Country</td>  
  19.                 </tr>  
  20.             }  
  21.         </tbody>  
  22.     </table>  
  23. </div> 
OUTPUT
 
During page load event.
 
 
 
Mobile view support.
 
 
 
Gif image for better understanding about output.
 
 
 
Check sql server for inserting records as shown in the above image.
 
 
 
Link To Source Code
SUMMARY