Sunday, March 10, 2013

How to consume ASP.NET WebAPI from jQuery

Before some months Microsoft has launched WebAPI framework for building and consuming HTTP services. This WebAPI can be called from anything like from mobile sites to JavaScript anything. I thought it will be a good idea to call a WebAPI from jQuery.

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 .

How to Create Webp API in Visual studio 2012

Now once you click Ok. It will ask for type of project. You want to create you need to select Web API there.

Create New WebAPI in visual studio 2012

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.

ASPNETWebAPIURL

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.

JqueryWebAPICosumeDemo

That’s it. Hope you like it. Stay tuned for more..

Shout it
Share:

2 comments:

  1. Hi, What if API has more than one mehtod, how to call them via jquery.

    ReplyDelete
  2. Malay, If you see the code carefully. You will see that type:get here you can write any method that are in web api

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews