In this post I am going to explain how to consume ASP.NET WebAPI from jQuery.
Creating a basic WebAPI:
To create a web API you need to install ASP.NET MVC 4.0 and then you create a new project for MVC .Now once you click Ok. It will ask for type of project. You want to create you need to select Web API there.
Once you click ok it will create a new WebAPI project.
Consuming Web API with jQuery:
I have written following code for the hello world api which we are going to consume from the jquery.using System.Web.Http; namespace jQueryWebAPI.Controllers { public class HelloWorldController : ApiController { public string Get() { return "Hello World"; } } }Now our ASP.NET WebAPI is ready use when you run this in browser it will look like this.
As now our we api is ready to use. Let’s write Jquery code to consume that Web API. I have created a html button for that and from that I will call a JavaScript function from from where we will call $ajax method of jquery to consume webapi. Following is a HTML code for button.
<input type="submit" value="Hello World" onclick="GetHelloWorld()"/>
Below is the code for JavaScript function "GetHelloWorld".
function GetHelloWorld() { $.ajax({ url: 'http://localhost:3512/API/HelloWorld', type: 'GET', dataType: 'json', success: function (data) { alert(data); }, error: function() { alert("Error Occured"); } }); }
Now let’s run browser in browser and click on that button. Following is a output as expected.
That’s it. Hope you like it. Stay tuned for more..
Hi, What if API has more than one mehtod, how to call them via jquery.
ReplyDeleteMalay, If you see the code carefully. You will see that type:get here you can write any method that are in web api
ReplyDelete