Calling the ASP.Net Web API With jQuery and JavaScript

Introduction

In this article we will use jQuery and JavaScript for calling the Web API. We know that the ASP. Net Web API is a framework for creating Web APIs of the .NET Framework. In this article we will use the ASP. Net Web API to create a Web API that returns a list of items.
Now we will provide the procedure for creating the Web API.

Step 1

First we create the Web API project as in the following:

  • Open Visual Studio 2012 and select "File" -> "New" -> "Project...".
  • In the Template Window select Visual C# >Web and then select "ASP. Net MVC 4 Web Application". Change the name of this to "ExampleAPI" and click on the "OK" button.
example.jpg

In the New ASP. Net MVC 4 project window select "Web API" and click the "OK" button.

exampl1.jpg

Step 2

Now we Add a Model

In the ASP. Net Web API the Model can be serialized automatically in Java Script Object Notation (JSON) and Extensible Markup Language (XML) format. We can use the model to represent the data  in our application.
Now we will describe how to create the model in the application.

  • In the Solution Explorer right-click on the "Model" folder
  • From the context menu select "Add" and select the class
ex1.jpg

Step 3

We change the class name to "Item" and add this code to the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ExampleAPI.Models
{
   
public class Item
    {
       
public int Id { get; set; }
       
public string name { get; set; }
       
public string Type { get; set; }
       
public decimal cost { get; set; }
    }
}

Step 4

Add the Controller

The Controller handles the HTTP requests. There are two types of controllers; they are:

HomeController: used for serving the HTML pages to the WebSite. It cannot have direct interaction with the Web API.
ValuesController: works as an example of the Web API.

Use the following to add the controller:

  • In the Solution Explorer right-click on the "Controller" folder.
  • Select "Add and Select Controller".
  • Change the name of the controller to "Items".
  • In the Template select "Empty API Controller".
example 3.jpg


cont.jpg

Now add the following code to the Controller.

namespace ExampleAPI.Controllers

{

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

    using ExampleAPI.Models;

 

    public class ItemsController : ApiController

    {

        Item[] items = new Item[]

        {

            new Item{Id = 1,name="Apple", Type="Fruit",cost=100},

            new Item{Id = 2,name="Tomato",Type="vasitable",cost=50},

        new Item {Id = 3,name="T-Shirt",Type="cloths",cost=500}

        };

        public IEnumerable<Item> GetAllItems()

        {

            return items;

        }

        public Item GetItemById(int id)

        {

            var item = items.FirstOrDefault((I) => I.Id == id);

            if (item == null)

            {

                throw new HttpResponseException(HttpStatusCode.NotFound);

            }

            return item;

        }

        public IEnumerable<Item>GetItemsByType(string type)

        {

 

            return items.Where(

                (I) => string.Equals(I.Type, type,

                    StringComparison.OrdinalIgnoreCase));

        }

    }

}

Step5

For calling the Web API with jQuery an JavaScript

In the Solution Explorer, expand the Home Folder and double-click on the Index.cshtml.

cshtml.jpg

 And write this code.

<!DOCTYPE html>

<html lang="en">

<head>

    <title>ASP.NET Web API</title>

    <link href="../../Content/Site.css" rel="stylesheet" />

    <script src="../../Scripts/jquery-1.7.1.min.js"

        type="text/javascript"></script>

        <script type="text/javascript">

            $(document).ready(function ()

{

                 $.getJSON("api/items/",

                function (Data) {

 

                    $.each(Data, function (key, val)

{

                    var str = val.name + ': $' + val.cost;

                        $('<li/>', { text: str })

                        .appendTo($('#items'));

                    });

                });

            });

 

            function show() {

                var Id = $('#itId').val();

                $.getJSON("api/items/" + Id,

                    function (Data) {

                        var str = Data.name + ': $' + Data.cost;

                        $('#items').text(str);

                    })

                .fail(

                    function (jqXHR, textStatus, err) {

                        $('#items').text('Error: ' + err);

                    });

            }

        </script>

 

</head>

<body id="body" >

    <div class="main-content">

        <div>

            <h1>Showing All Items </h1>

            <ul id="items"/>

        </div>

        <div>

            <label for="itId">ID:</label>

            <input type="text" id="itId" size="5"/>

            <input type="button" value="Search" onclick="show();" />

            <p id="item" />

        </div>

    </div>

</body>

</html>

Result

 resultex.jpg

 Search the Item Through Id

resultex2.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all