ASP.NET Web API Using MVC, Entity Framework And jQuery For Get and Post With Validation - Part Five

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 Asp.net Web API or post data to 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.
Source Code
Steps to be followed.
 
Step 1
 
Apply validation on Model.

Go to Solution Explorer > Entities (Project name) > Satyadatabasemodel.tt> Open Employee.cs.
 
Code Ref
  1. //------------------------------------------------------------------------------  
  2. // <auto-generated>  
  3. //    This code was generated from a template.  
  4. //  
  5. //    Manual changes to this file may cause unexpected behavior in your application.  
  6. //    Manual changes to this file will be overwritten if the code is regenerated.  
  7. // </auto-generated>  
  8. //------------------------------------------------------------------------------  
  9.   
  10. namespace Entities  
  11. {  
  12.     using System;  
  13.     using System.Collections.Generic;  
  14.     using System.ComponentModel.DataAnnotations;  
  15.   
  16.     public partial class Employee  
  17.     {  
  18.         public int EmployeeID { getset; }  
  19.         [Required(ErrorMessage = "First name required", AllowEmptyStrings = false)]  
  20.         public string FirstName { getset; }  
  21.         [Required(ErrorMessage = "Last name required", AllowEmptyStrings = false)]  
  22.         public string LastName { getset; }  
  23.         [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",  
  24.             ErrorMessage = "E-mail is not valid")]  
  25.         public string EmailID { getset; }  
  26.         public string City { getset; }  
  27.         public string Country { getset; }  
  28.     }  

Code Description
 
Here, I have applied validation on firstname, lastname, and email field. If the first name and last name will be empty, then the validation message will be displayed. For email field, if the user will input invalid mail address with incorrect domain address, then the email validation message will be shown to the end user.
 
Step 2
 
Add a new Action to the SatyaController of SatyaWebApi Web API project for Post Data.
 
Code Ref
  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 Entities;    
  8.     
  9. namespace SatyaWebApi.Controllers    
  10. {    
  11.     public class SatyaController : ApiController    
  12.     {    
  13.           
  14.         public HttpResponseMessage Get()    
  15.         {    
  16.             List<Employee> allEmp = new List<Employee>();    
  17.             using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  18.             {    
  19.                 allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();  
  20.                 HttpResponseMessage response;    
  21.                 response = Request.CreateResponse(HttpStatusCode.OK, allEmp);    
  22.                 return response;    
  23.             }    
  24.         }    
  25.         public HttpResponseMessage Post(Employee emp)    
  26.         {    
  27.             HttpResponseMessage response;    
  28.             if (ModelState.IsValid)    
  29.             {    
  30.                 using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())    
  31.                 {    
  32.                     dc.Employees.Add(emp);    
  33.                     dc.SaveChanges();    
  34.                 }    
  35.                 response = Request.CreateResponse(HttpStatusCode.Created, emp);    
  36.     
  37.                 //added for get    
  38.     
  39.                 List<Employee> allEmp = new List<Employee>();    
  40.                 using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  41.                 {    
  42.                     allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();    
  43.                     HttpResponseMessage response1;    
  44.                     response1 = Request.CreateResponse(HttpStatusCode.OK, allEmp);    
  45.                     return response1;    
  46.                 }    
  47.             }    
  48.     
  49.             else    
  50.             {    
  51.                 response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Please try again with valid data.");    
  52.             }    
  53.             return response;    
  54.         }    
  55.     }    
  56. }   
Code Description
 
In this code, I have added post controller action method to perform post data as well as added code about retrieving data inside post action method. The below code is for retrieving the data.
  1. //added for get      
  2.       
  3.                 List<Employee> allEmp = new List<Employee>();      
  4.                 using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())    
  5.                 {      
  6.                     allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();      
  7.                     HttpResponseMessage response1;      
  8.                     response1 = Request.CreateResponse(HttpStatusCode.OK, allEmp);      
  9.                     return response1;      
  10.                 }   
Code to insert data,
  1. HttpResponseMessage response;  
  2.            if (ModelState.IsValid)  
  3.            {  
  4.                using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
  5.                {  
  6.                    dc.Employees.Add(emp);  
  7.                    dc.SaveChanges();  
  8.                }  
  9.                response = Request.CreateResponse(HttpStatusCode.Created, emp); 
  1. dc.Employees.Add(emp);  
  2.  dc.SaveChanges(); 
Here, using datacontext object adds data and passes to the emp parameter in post action method and saves all changes made in this to the underlying database. 
  1. else  
  2.             {  
  3.                 response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Please try again with valid data.");  
  4.             } 
If any connection issue will be found or any related issue in code or invalid data during post operation then the error message will be shown to the end user.
 
Step 3
 
Add a new Action to the HomeController in SatyaConsumingApi for getting view to Post data.
 
Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using Entities;  
  8.   
  9. namespace SatyaConsumingApi.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         public ActionResult Part1()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         public ActionResult Part2()  
  19.         {  
  20.             List<Employee> list = new List<Employee>();  
  21.             HttpClient client = new HttpClient();  
  22.             var result = client.GetAsync("http://localhost:47250/api/satya").Result;  
  23.             if (result.IsSuccessStatusCode)  
  24.             {  
  25.                 list = result.Content.ReadAsAsync<List<Employee>>().Result;  
  26.             }  
  27.             return View(list);  
  28.         }  
  29.         public ActionResult Part3()  
  30.         {  
  31.             return View();  
  32.         }  
  33.   
  34.     }  

Code Description
 
Here Part 3 is the new controller action mentiod in MVC client application.
 
Step 4
 
Add view for the Action.
 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Satyaprakash - Post Data To Web API Using jQuery With Validation";  
  3. }  
  4.   
  5. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  7. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  8.   
  9.   
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">  
  11.   
  12. </script>  
  13.   
  14. <style>  
  15.     .error, #error {  
  16.         color: red;  
  17.         display: none;  
  18.     }  
  19.   
  20.     table {  
  21.         font-family: arial, sans-serif;  
  22.         border-collapse: collapse;  
  23.         width: 100%;  
  24.     }  
  25.   
  26.     td, th {  
  27.         border: 1px solid #dddddd;  
  28.         text-align: left;  
  29.         padding: 8px;  
  30.     }  
  31.   
  32.     tr:nth-child(even) {  
  33.         background-color: #dddddd;  
  34.     }  
  35.   
  36.     .button {  
  37.         background-color: #4CAF50;  
  38.         border: none;  
  39.         color: white;  
  40.         padding: 15px 32px;  
  41.         text-align: center;  
  42.         text-decoration: none;  
  43.         display: inline-block;  
  44.         font-size: 16px;  
  45.         margin: 4px 2px;  
  46.         cursor: pointer;  
  47.     }  
  48.   
  49.     .button4 {  
  50.         border-radius: 9px;  
  51.     }  
  52. </style>  
  53.   
  54. <div style="padding:10px ; align-content:center">  
  55.     <fieldset>  
  56.         <legend style="font-family:Arial Black;color:blue">Post Data To Web API Using jQuery With Validation</legend>  
  57.     </fieldset>  
  58. </div>  
  59.   
  60. <div class="container1">  
  61.     <form id="frm1" role="form" style="max-width:500px">  
  62.         <div class="form-group">  
  63.             <div id="error"> </div>  
  64.         </div>  
  65.         <div class="form-group">  
  66.             <label for="firstname" style="color:blue">First Name:</label>  
  67.             <input type="text" class="form-control" id="firstname" placeholder="please enter First Name">  
  68.             <span class="error">Please provide First Name</span>  
  69.         </div>  
  70.         <div class="form-group">  
  71.             <label for="lastname" style="color:blue">Last Name:</label>  
  72.             <input type="text" class="form-control" id="lastname" placeholder="please enter Last Name">  
  73.             <span class="error">Please provide Last Name</span>  
  74.         </div>  
  75.         <div class="form-group">  
  76.             <label for="email" style="color:blue">Email:</label>  
  77.             <input type="text" class="form-control" id="email" placeholder="please enter Email-Id">  
  78.             <span class="error">Invalid email ID</span>  
  79.         </div>  
  80.         <div class="form-group">  
  81.             <label for="city" style="color:blue">City:</label>  
  82.             <input type="text" class="form-control" id="city" placeholder="please enter City">  
  83.         </div>  
  84.         <div class="form-group">  
  85.             <label for="country" style="color:blue">Country:</label>  
  86.             <input type="text" class="form-control" id="country" placeholder="please enter Country">  
  87.         </div>  
  88.         <button type="submit" class="button button4">Submit</button>  
  89.     </form>  
  90. </div>  
  91.   
  92. <div id="updatePanel" style="width:90%; margin:0 auto; padding:10px">  
  93.   
  94. </div>  
  95.   
  96. @section Scripts{  
  97.     <script>  
  98.             $(document).ready(function () {  
  99.                 var apiBaseUrl = "http://localhost:47250/";  
  100.                 $('#frm1').submit(function (e) {  
  101.                     e.preventDefault();  
  102.                     var isOK = ValidateForm();  
  103.                     if (isOK) {  
  104.                         var emp = {  
  105.                             EmployeeID: 0,  
  106.                             FirstName: $('#firstname').val().trim(),  
  107.                             LastName: $('#lastname').val().trim(),  
  108.                             EmailID: $('#email').val().trim(),  
  109.                             City: $('#city').val().trim(),  
  110.                             Country: $('#country').val().trim()  
  111.                         };  
  112.   
  113.                         //Save  
  114.                         $.ajax({  
  115.                             url: apiBaseUrl+'api/satya',  
  116.                             type: 'POST',  
  117.                             dataType: 'json',  
  118.                             data: emp,  
  119.                             success: function (d) {  
  120.                                 bootbox.alert('Data Is Successfully Saved!');  
  121.                                 var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  122.                                 var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Full Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  123.                                 $table.append($header);  
  124.                                 $.each(d, function (i, val) {  
  125.                                     var $row = $('<tr/>');  
  126.                                     $row.append($('<td/>').html(val.FirstName + ' ' + val.LastName));  
  127.                                     $row.append($('<td/>').html(val.EmailID));  
  128.                                     $row.append($('<td/>').html(val.City));  
  129.                                     $row.append($('<td/>').html(val.Country));  
  130.                                     $table.append($row);  
  131.                                 });  
  132.                                 $('#updatePanel').html($table);  
  133.   
  134.                                 var frm = document.getElementById('frm1');  
  135.                                 frm.reset();  
  136.                             },  
  137.                             error: function () {  
  138.                                 $('#error').html('Error! please try with valid data.').show();  
  139.                             }  
  140.                         });  
  141.                     }  
  142.                 });  
  143.             });  
  144.             function ValidateForm() {  
  145.                 var isAllValid = true;  
  146.                 $('.error').hide();  
  147.                 $('#error').empty();  
  148.                 $('.form-group').removeClass('has-error');  
  149.                 if ($('#firstname').val().trim()=="") {  
  150.                     $('#firstname').focus();  
  151.                     $('#firstname').siblings('.error').show();  
  152.                     $('#firstname').parents('.form-group').addClass('has-error');  
  153.                     isAllValid = false;  
  154.                 }  
  155.                 if ($('#lastname').val().trim() == "") {  
  156.                     $('#lastname').focus();  
  157.                     $('#lastname').siblings('.error').show();  
  158.                     $('#lastname').parents('.form-group').addClass('has-error');  
  159.                     isAllValid = false;  
  160.                 }  
  161.                 if ($('#email').val().trim() != "") {  
  162.   
  163.                     var expr = /^([a-zA-Z0-9_\-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;  
  164.                     if (!expr.test($('#email').val().trim())) {  
  165.                         $('#email').focus();  
  166.                         $('#email').siblings('.error').show();  
  167.                         $('#email').parents('.form-group').addClass('has-error');  
  168.                         isAllValid = false;  
  169.                     }  
  170.                 }  
  171.                 return isAllValid;  
  172.             }  
  173.     </script>  

Code Description
 
I created a  script function to validate form control named "ValidateForm()" . If successfully validated then post data operation will be performed and then it will retrieve the data after successful post operation. Then all input fields will be reset else the error message will be shown  due to invalid data.
  1. $.ajax({  
  2.                             url: apiBaseUrl+'api/satya',  
  3.                             type: 'POST',  
  4.                             dataType: 'json',  
  5.                             data: emp,  
  6.                             success: function (d) {  
  7.                                 bootbox.alert('Data Is Successfully Saved!');  
  8.                                 var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  9.                                 var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Full Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  10.                                 $table.append($header);  
  11.                                 $.each(d, function (i, val) {  
  12.                                     var $row = $('<tr/>');  
  13.                                     $row.append($('<td/>').html(val.FirstName + ' ' + val.LastName));  
  14.                                     $row.append($('<td/>').html(val.EmailID));  
  15.                                     $row.append($('<td/>').html(val.City));  
  16.                                     $row.append($('<td/>').html(val.Country));  
  17.                                     $table.append($row);  
  18.                                 });  
  19.                                 $('#updatePanel').html($table);  
  20.   
  21.                                 var frm = document.getElementById('frm1');  
  22.                                 frm.reset();  
  23.                             },  
  24.                             error: function () {  
  25.                                 $('#error').html('Error! please try with valid data.').show();  
  26.                             }  
  27.                         }); 
The CDN reference should be added for bootbox alert message support.
  1. bootbox.alert('Data Is Successfully Saved!'); 
  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">  
  2.   
  3. </script> 
Step 5
 
Add bootstrap css for a good appearnace in _Layout.cshtml.
  1. @* @Styles.Render("~/Content/css")*@  
  2.     @* Add bootstrap css for good looks *@  
  3.     <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />  
  4.     @Scripts.Render("~/bundles/modernizr"
OUTPUT
 
The Part 3 view will look as shown below..
 
  
For First and Last Name Validations....
 
 
For Email field validation..
 
  
For a successful alert message post data using bootbox javascript library.
 
 
 
After successful post data get data or bind data into table.
 
 
 
Check Database for record insert operation.
 
 
 
Responsive web page for tablets and mobile phones.
 
 
 
Gif image for better understanding.
 
  
 
SUMMARY
  • Post and Get operation using one controller action method in Asp.Net Web API.
  • Post data with form control validation.
  • Bootbox javascript library for alert message.
  • Mobile responsive support.


Similar Articles