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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace SatyaprakashjQueryPostCallToWebAPI2Controller.Models
- {
- public class PersonModel
- {
-
-
-
- public string Name { get; set; }
-
-
-
-
- public string DateTime { get; set; }
- }
- }
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
- using SatyaprakashjQueryPostCallToWebAPI2Controller.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
-
- namespace SatyaprakashjQueryPostCallToWebAPI2Controller.Controllers
- {
- public class AjaxAPIController : ApiController
- {
- [Route("api/AjaxAPI/AjaxMethod")]
- [HttpPost]
- public PersonModel AjaxMethod(PersonModel person)
- {
- person.DateTime = DateTime.Now.ToString();
- return person;
- }
- }
- }
Code Description
Important Namespaces should be added.
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
Here, I created Controller using Web API 2; that's why the code looks like this:
- 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.
- [Route("api/AjaxAPI/AjaxMethod")]
- [HttpPost]
- public PersonModel AjaxMethod(PersonModel person)
- {
- person.DateTime = DateTime.Now.ToString();
- return person;
- }
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Http;
- using System.Web.Mvc;
- using System.Web.Optimization;
- using System.Web.Routing;
-
- namespace SatyaprakashjQueryPostCallToWebAPI2Controller
- {
- public class MvcApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- }
- }
- }
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.
- 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
- using SatyaprakashjQueryPostCallToWebAPI2Controller.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace SatyaprakashjQueryPostCallToWebAPI2Controller.Controllers
- {
- public class HomeController : Controller
- {
-
-
- public ActionResult Index()
- {
- return View();
- }
- }
- }
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
- @{
- ViewBag.Title = "Satyaprakash jQuery Post Call To Web API 2 Controller";
- }
- <title>@ViewBag.Title</title>
-
- <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">Satyaprakash jQuery Post Call To Web API 2 Controller</h2>
-
- <style>
- .button {
- background-color: #4CAF50;
- border: none;
- color: white;
- padding: 15px 32px;
- text-align: center;
- text-decoration: none;
- display: inline-block;
- font-size: 16px;
- margin: 4px 2px;
- cursor: pointer;
- }
-
- .button4 {
- border-radius: 9px;
- }
-
- input[type=text], select {
- width: 20%;
- padding: 12px 20px;
- margin: 10px 0;
- display: inline-block;
- border: 1px solid #ccc;
- border-radius: 4px;
- box-sizing: border-box;
- align-content: center;
- align-self: center;
- }
-
- .bootbox-alert div div div button.btn-primary {
- background-color: green;
- font-size: 20px;
- }
-
- .bootbox-body {
- font-size: 20px;
- color: #f40;
- }
- </style>
-
- <fieldset>
- <legend style="color: Blue">Get Updated Time</legend>
-
- <input type="text" id="txtName" placeholder="Enter Your Name...." />
- <input type="button" id="btnGet" class="button button4" value="Show Time" />
-
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
-
- <script src="bootbox.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">
- </script>
-
- <script type="text/javascript">
- $(function () {
- $("#btnGet").click(function () {
- var person = '{Name: "' + $("#txtName").val() + '" }';
- $.ajax({
- type: "POST",
- url: "/api/AjaxAPI/AjaxMethod",
- data: person,
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
- bootbox.alert("Hi, " + response.Name + ".\nCurrent Date and Time Is: " + response.DateTime);
- },
- failure: function (response) {
- bootbox.alert(response.responseText);
- },
- error: function (response) {
- bootbox.alert(response.responseText);
- }
- });
- });
- });
- </script>
-
- </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.
- <script type="text/javascript">
- $(function () {
- $("#btnGet").click(function () {
- var person = '{Name: "' + $("#txtName").val() + '" }';
- $.ajax({
- type: "POST",
- url: "/api/AjaxAPI/AjaxMethod",
- data: person,
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
- bootbox.alert("Hi, " + response.Name + ".\nCurrent Date and Time Is: " + response.DateTime);
- },
- failure: function (response) {
- bootbox.alert(response.responseText);
- },
- error: function (response) {
- bootbox.alert(response.responseText);
- }
- });
- });
- });
- </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.
- $("#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.
- url: "/api/AjaxAPI/AjaxMethod",
The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
- success: function (response) {
- bootbox.alert("Hi, " + response.Name + ".\nCurrent Date and Time Is: " + response.DateTime);
- }
The customized code is given below for bootbox layout stuff:
Summary
In this article we learned the following:
- What the Web API 2 Controller is.
- How we can set communication between Web API 2 Controller and jQuery.
- The implementation of both the above parts using ASP.NET MVC Razor.