jQuery AJAX GET & POST Data Using MVC Web API

The article basically describes the following GET and POST methods: 

  • POST: Create
  • GET: Read

The Web API is also called RESTful services because we can call these services using an URL and these type of services are helpful for mobiles and they are platform-independent.

Let us start to create a WebAPI first. First we will create controller.cs.

Suppose we have added a HomeController.cs.

  1. public class HomeController : ApiController  
  2. {  
  3.      public string GetEmployeeInformation(string JSONString)  
  4.      {  
  5.          var seriptSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();  
  6.          Employee employee = seriptSerialization.Deserialize<Employee>(JSONString);  
  7.          //if list then we can use like this  
  8.          //List<Employee> employee = seriptSerialization.Deserialize<List<Employee>>(JSONString);  
  9.          return employee.EmployeeName;  
  10.      }  
  11.   
  12.      public string PostSubmitdata([FromBody]Employee emp)  
  13.      {  
  14.          return emp.EmployeeName;  
  15.      }  
  16. }  
And the Employee class:
  1. public class Employee  
  2. {  
  3.        public string EmployeeName { getset; }  
  4.        public EmployeeDetails empdetails { getset; }  
  5. }  
  6. public class EmployeeDetails  
  7. {  
  8.        public string email { getset; }  
  9.        public string firstName { getset; }  
  10.        public string lastName { getset; }  
  11. }  
Then we will look at the WebApiConfig.cs file in the App_Start folder.

So we can see the default route setting is given below, but in this route we cannot add an Action or method name. 
  1. public static void Register(HttpConfiguration config)  
  2.         {  
  3.             config.Routes.MapHttpRoute(  
  4.                 name: "DefaultApi",  
  5.                 routeTemplate: "api/{controller}/{id}",  
  6.                 defaults: new { id = RouteParameter.Optional }  
  7.             );  
  8.         }  
So we will amend this default route to this setting, here we have also added an action name.
  1. public static void Register(HttpConfiguration config)  
  2.         {  
  3.             config.Routes.MapHttpRoute(  
  4.                 name: "DefaultApi",  
  5.                 routeTemplate: "api/{controller}/{action}/{id}",  
  6.                 defaults: new { id = RouteParameter.Optional }  
  7.             );  
  8.         }  
So we can write the GET and POST methods as shown below.
  1. <!DOCTYPE>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  6.     <script language="javascript" type="text/javascript">  
  7.           
  8.         /**********************************Request****************************************/  
  9.         var reqdata = {  
  10.             EmployeeName: "JD Mishra",  
  11.             empdetails: {  
  12.                 email: '[email protected]',  
  13.                 firstName: 'Jagdev',  
  14.                 lastName: 'Mishra'  
  15.             }  
  16.         }  
  17.         var stringReqdata = JSON.stringify(reqdata);  
  18.   
  19.         /*************************************GET*****************************************/  
  20.         function GetEmployeeInformation() {  
  21.             var url = "http://localhost:4000/api/Home/GetEmployeeInformation?JSONString=" + stringReqdata;  
  22.             jQuery.ajax({  
  23.                 dataType: "json",  
  24.                 url: url,  
  25.                 async: false,  
  26.                 context: document.body  
  27.             }).success(function (data) {  
  28.                 alert(data);  
  29.             });  
  30.         };  
  31.         /*************************************GET*****************************************/  
  32.         function PostSubmitdata() {  
  33.             var url = "http://localhost:4000/api/Home/PostSubmitdata";  
  34.             jQuery.ajax({  
  35.                 async: false,  
  36.                 type: "POST",  
  37.                 url: url,  
  38.                 data: stringReqdata,  
  39.                 dataType: "json",  
  40.                 context: document.body,  
  41.                 contentType: 'application/json; charset=utf-8'  
  42.             }).success(function (data) {  
  43.                 alert(data);  
  44.             })  
  45.         }  
  46.     </script>  
  47. </head>  
  48. <body>  
  49.     <a href="#" onclick="GetEmployeeInformation();">Get</a><br />  
  50.     <a href="#" onclick="PostSubmitdata();">Post</a>  
  51. </body>  
  52. </html>  
Thanks

Up Next
    Ebook Download
    View all
    Learn
    View all