Introduction To jQuery And Web API 2 Controller’s Method Relationship Using jQuery AJAX In ASP.NET MVC Razor

Introduction

ASP.NET Web API is a smart framework to build HTTP services which can be consumed by multi-platform clients, including desktops or smart phone devices regardless of browsers or Operating Systems being used. ASP.NET Web API supports RESTful applications and uses GET, PUT, POST, DELETE verbs for client communications.

Description

Here, I will show you how jQuery POST Calls to Web API 2 Controller method using jQuery AJAX in ASP.NET MVC Razor. I designed a web page using MVC and put a text box and a button.The text box will be asking your name. By putting your name, when you click on the button, an alert message will show you the current date & time with your name.

This date-time comes from the Web API 2 Controller method by calling through jQuery Post call in ASP.NET MVC.

Steps to be followed,

Step 1

First, create an MVC 4.5 application named "SatyaprakashjQueryPostCallToWebAPI2Controller".
 
 
 
Step 2

Then create a Model Class file named "PersonModel.cs".

Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace SatyaprakashjQueryPostCallToWebAPI2Controller.Models  
  7. {  
  8.     public class PersonModel  
  9.     {  
  10.         ///<summary>  
  11.         /// Gets or sets Name.  
  12.         ///</summary>  
  13.         public string Name { getset; }  
  14.   
  15.         ///<summary>  
  16.         /// Gets or sets DateTime.  
  17.         ///</summary>  
  18.         public string DateTime { getset; }  
  19.     }  
  20. }  
Code Description

Model Class named PersonModel has two properties which are Name and DateTime. Here, by using the Name property, the alert will show you the name and by using the DateTime property, it will also show the updated date and time.

Step 3

In order to add a Web API Controller, you will need to right click the Controllers folder in the Solution Explorer and click on Add >> Controller.

Now, from the "Add" cascading window, choose the "Web API 2 Controller – Empty" option, as shown below.
 
 
 
The Controller popup will appear.



Now give it a proper name and click OK.

 
Code Ref
  1. using SatyaprakashjQueryPostCallToWebAPI2Controller.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8.   
  9. namespace SatyaprakashjQueryPostCallToWebAPI2Controller.Controllers  
  10. {  
  11.     public class AjaxAPIController : ApiController  
  12.     {  
  13.         [Route("api/AjaxAPI/AjaxMethod")]  
  14.         [HttpPost]  
  15.         public PersonModel AjaxMethod(PersonModel person)  
  16.         {  
  17.             person.DateTime = DateTime.Now.ToString();  
  18.             return person;  
  19.         }  
  20.     }  
  21. }  
Code Description

Important Namespaces should be added.
  1. using System.Net;  
  2. using System.Net.Http;  
  3. using System.Web.Http; 
Here, I created Controller using Web API 2; that's why the code looks like this:
  1. public class AjaxAPIController : ApiController 

The Web API Controller consists of a method named AjaxMethod which accepts an object of PersonModel and updates the DateTime property with the Current Date and Time and returns it back. This method is decorated with the Route attribute which defines its Route for calling the Web API method and HttpPost attribute which then signifies that the method will accept Http Post requests.

  1. [Route("api/AjaxAPI/AjaxMethod")]  
  2.         [HttpPost]  
  3.         public PersonModel AjaxMethod(PersonModel person)  
  4.         {  
  5.             person.DateTime = DateTime.Now.ToString();  
  6.             return person;  
  7.         }  
Step 4

The next task is to register the configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.

Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Http;  
  6. using System.Web.Mvc;  
  7. using System.Web.Optimization;  
  8. using System.Web.Routing;  
  9.   
  10. namespace SatyaprakashjQueryPostCallToWebAPI2Controller  
  11. {  
  12.     public class MvcApplication : System.Web.HttpApplication  
  13.     {  
  14.         protected void Application_Start()  
  15.         {  
  16.             AreaRegistration.RegisterAllAreas();  
  17.             System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);  
  18.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  19.         }  
  20.     }  
  21. }  
Code Description

The line mentioned below is important to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
  1. System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);  
Step 5

Now, you will need to add one empty Controller along with a View. The View will be used for calling the Web API 2 Controller method using jQuery AJAX. The Controller consists of an empty Action method which then simply returns the View.

 
Code Ref
  1. using SatyaprakashjQueryPostCallToWebAPI2Controller.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace SatyaprakashjQueryPostCallToWebAPI2Controller.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /Home/  
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.     }  
  19. }  
Code Description

Using "Home" as Controller name and "Index" as Controller action method name.

Step 6

The next step is to add an Empty View without a Model for the Controller. The View consists of an HTML TextBox element and a button. The button has been assigned a jQuery click event handler and when clicked, a jQuery AJAX call is made to the Web API 2 Controller’s method.

The URL for the jQuery AJAX call is set to the Web API 2 Controller’s method. i.e. api/AjaxAPI/AjaxMethod. The value of the TextBox is passed as parameter and the returned response is displayed using a JavaScript Alert Message Box. 
 
 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Satyaprakash jQuery Post Call To Web API 2 Controller";  
  3. }  
  4. <title>@ViewBag.Title</title>  
  5.   
  6. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">Satyaprakash jQuery Post Call To Web API 2 Controller</h2>  
  7.   
  8. <style>  
  9.     .button {  
  10.         background-color: #4CAF50;  
  11.         border: none;  
  12.         color: white;  
  13.         padding: 15px 32px;  
  14.         text-align: center;  
  15.         text-decoration: none;  
  16.         display: inline-block;  
  17.         font-size: 16px;  
  18.         margin: 4px 2px;  
  19.         cursor: pointer;  
  20.     }  
  21.   
  22.     .button4 {  
  23.         border-radius: 9px;  
  24.     }  
  25.   
  26.     input[type=text], select {  
  27.         width: 20%;  
  28.         padding: 12px 20px;  
  29.         margin: 10px 0;  
  30.         display: inline-block;  
  31.         border: 1px solid #ccc;  
  32.         border-radius: 4px;  
  33.         box-sizing: border-box;  
  34.         align-content: center;  
  35.         align-self: center;  
  36.     }  
  37.   
  38.     .bootbox-alert div div div button.btn-primary {  
  39.         background-color: green;  
  40.         font-size: 20px;  
  41.     }  
  42.   
  43.     .bootbox-body {  
  44.         font-size: 20px;  
  45.         color: #f40;  
  46.     }  
  47. </style>  
  48.   
  49. <fieldset>  
  50.     <legend style="color: Blue">Get Updated Time</legend>  
  51.   
  52.     <input type="text" id="txtName" placeholder="Enter Your Name...." />  
  53.     <input type="button" id="btnGet" class="button button4" value="Show Time" />  
  54.   
  55.     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  56.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  57.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  58.     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  59.   
  60.     <script src="bootbox.min.js"></script>  
  61.     <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">  
  62.     </script>  
  63.   
  64.     <script type="text/javascript">  
  65.         $(function () {  
  66.             $("#btnGet").click(function () {  
  67.                 var person = '{Name: "' + $("#txtName").val() + '" }';  
  68.                 $.ajax({  
  69.                     type: "POST",  
  70.                     url: "/api/AjaxAPI/AjaxMethod",  
  71.                     data: person,  
  72.                     contentType: "application/json; charset=utf-8",  
  73.                     dataType: "json",  
  74.                     success: function (response) {  
  75.                         bootbox.alert("Hi, " + response.Name + ".\nCurrent Date and Time Is: " + response.DateTime);  
  76.                     },  
  77.                     failure: function (response) {  
  78.                         bootbox.alert(response.responseText);  
  79.                     },  
  80.                     error: function (response) {  
  81.                         bootbox.alert(response.responseText);  
  82.                     }  
  83.                 });  
  84.             });  
  85.         });  
  86.     </script>  
  87.   
  88. </fieldset>  
Code Description

Here, the name of the View is "Index". The full method of applying CSS and Bootstrap to the textbox and button is already described in my previous articles. So, let's discuss the new code section, as mentioned below. 
  1. <script type="text/javascript">  
  2.         $(function () {  
  3.             $("#btnGet").click(function () {  
  4.                 var person = '{Name: "' + $("#txtName").val() + '" }';  
  5.                 $.ajax({  
  6.                     type: "POST",  
  7.                     url: "/api/AjaxAPI/AjaxMethod",  
  8.                     data: person,  
  9.                     contentType: "application/json; charset=utf-8",  
  10.                     dataType: "json",  
  11.                     success: function (response) {  
  12.                         bootbox.alert("Hi, " + response.Name + ".\nCurrent Date and Time Is: " + response.DateTime);  
  13.                     },  
  14.                     failure: function (response) {  
  15.                         bootbox.alert(response.responseText);  
  16.                     },  
  17.                     error: function (response) {  
  18.                         bootbox.alert(response.responseText);  
  19.                     }  
  20.                 });  
  21.             });  
  22.         });  
  23.     </script> 
The Button has been assigned a jQuery click event handler and when clicked, a jQuery AJAX call is made to the Web API 2 Controller’s method.
  1. $("#btnGet").click(function () 
The URL for the jQuery AJAX call is set to the Web API 2 Controller’s method i.e. api/AjaxAPI/AjaxMethod. 
  1. url: "/api/AjaxAPI/AjaxMethod"
The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
  1. success: function (response) {  
  2.                         bootbox.alert("Hi, " + response.Name + ".\nCurrent Date and Time Is: " + response.DateTime);  
  3.                     } 
The customized code is given below for bootbox layout stuff:
  1. .bootbox-alert div div div button.btn-primary {  
  2.        background-color: green;  
  3.        font-size: 20px;  
  4.    }  
  5.   
  6.    .bootbox-body {  
  7.        font-size: 20px;  
  8.        color: #f40;  
  9.    }  
OUTPUT

Desktop View



Mobile View



Here, I have customized the bootbox layout like button and text.

 
Summary

In this article we learned the following:
  1. What the Web API 2 Controller is.
  2. How we can set communication between Web API 2 Controller and jQuery.
  3. The implementation of both the above parts using ASP.NET MVC Razor.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now