In this article I will explain with an example, how to make a jQuery POST telephone call to Spider web API two Controller's method using jQuery AJAX in ASP.Net MVC Razor.

What is Web API?

ASP.Net Web API is a framework to build HTTP services which can be consumed by cross platform clients including desktops or mobile devices irrespective of the Browsers or Operating Systems beingness used.

ASP.Internet Web API supports RESTful applications and uses GET, PUT, POST, DELETE verbs for client communications.

Model

Following is a Model class named PersonModel with two backdrop i.e. Name and DateTime.

public form PersonModel

{

/// <summary>

/// Gets or sets Name.

/// </summary>

public string Name { become ; set ; }

/// <summary>

/// Gets or sets DateTime.

/// </summary>

public string DateTime { become ; gear up ; }

}

Spider web API Controller

In club to add a Web API Controller you lot will need to Right Click the Controllers folder in the Solution Explorer and click on Add and and then Controller.

Now from the Add together Scaffold window, choose the Web API two Controller – Empty option as shown below.

jQuery AJAX: Post JSON data to Web API in ASP.Net MVC

Then give information technology a suitable proper name and click OK.

jQuery AJAX: Post JSON data to Web API in ASP.Net MVC

The next task is to annals the Configuration for Spider web API in the Global.asax file and so that the Web API is available for accessing on Web.

 In social club to do so open up Global.asax file and add the following line.

Arrangement.Spider web.Http. GlobalConfiguration .Configure( WebApiConfig .Annals);

Make sure you lot add information technology in the same order as shown below.

public course MvcApplication : System.Web. HttpApplication

{

protected void Application_Start()

    {

AreaRegistration .RegisterAllAreas();

        System.Web.Http. GlobalConfiguration .Configure( WebApiConfig .Annals);

RouteConfig .RegisterRoutes( RouteTable .Routes);

    }

}

The next footstep is to code the Web API Controller. The Web API Controller consists of a method named AjaxMethod which accepts an object of PersonModel and updates the DateTime holding with the Current Date and Time and returns information technology back.

This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will have Http Post requests.

public grade AjaxAPIController : ApiController

{

    [ Route ( "api/AjaxAPI/AjaxMethod" )]

    [ HttpPost ]

public PersonModel AjaxMethod( PersonModel person)

    {

        person.DateTime = DateTime .At present.ToString();

return person;

    }

}

Controller

At present you lot will need to add one empty Controller along with a View. The View will exist used for calling the Web API 2 Controller'due south method using jQuery AJAX.

The Controller consists of an empty Action method which but returns the View.

public class HomeController : Controller

{

// GET: Dwelling

public ActionResult Index()

    {

return View();

    }

}

View

Next footstep is to add together an Empty View without Model for the Controller.

The View consists of an HTML TextBox element and a Push button. The Button has been assigned a jQuery click event handler and when the Button is clicked a jQuery AJAX call is fabricated to the Web API 2 Controller's method.

The URL for the jQuery AJAX call is set to the Web API 2 Controller'southward method i.e. /api/AjaxAPI/AjaxMethod. The value of the TextBox is passed every bit parameter and the returned response is displayed using JavaScript Alert Message Box.

@{

    Layout = cypher ;

}

< !DOCTYPE html >

< html >

< head >

< meta name ="viewport" content ="width=device-width" />

< title > Alphabetize </ title >

</ caput >

< body >

< input blazon ="text" id ="txtName" />

< input type ="button" id ="btnGet" value ="Get Current Time" />

< script type ="text/javascript" src ="http://ajax.googleapis.com/ajax/libs/jquery/i.eight.three/jquery.min.js"></ script >

< script type ="text/javascript">

        $( role () {

            $( "#btnGet" ).click( office () {

var person = '{Proper noun: "' + $( "#txtName" ).val() + '" }' ;

                $.ajax({

                    type: "Mail service" ,

                    url: "/api/AjaxAPI/AjaxMethod" ,

                    data: person,

                    contentType: "application/json; charset=utf-eight" ,

                    dataType: "json" ,

                    success: office (response) {

                        alert( "Hello: " + response.Name + ".\nCurrent Appointment and Fourth dimension: " + response.DateTime);

                    },

                    failure: function (response) {

                        alarm(response.responseText);

                    },

                    error: function (response) {

                        alert(response.responseText);

                    }

                });

            });

        });

</ script >

</ body >

</ html >

Screenshot

jQuery AJAX: Post JSON data to Web API in ASP.Net MVC

Downloads