Using Web Api in MVC 4

Introduction

The Web API (Application Programming Interface) feature is based on a special kind of controller to an MVC framework application, it's normally as we do in MVC :). An API controller distinguishes itself from the normal controllers by the following:

Action methods return a model rather than an ActionResult in MVC, objects.

Action methods are selected based on the HTTP method used in the request. (We will elaborate on this a bit ahead as we go. :))

The model objects that are returned from an API controller action method are encoded as JSON/XML based on the browsers used and then sent to the client.

Background

We work using the normal MVC4 framework, choosing an empty template. There is also a Web API template but we cannot get to understand the procedure using that. Let's get deeper into the following procedure in the Code section.

Using the code

A Web API application is just a regular MVC framework app with the addition of a special kind of controller. Let's start with a small Demo for a better understanding. Let's go step-by-step.

Creating the Model and Repository

  1. public interface IReservationRepository{  
  2.    IEnumerable<Reservation> GetAll();   
  3.    Reservation Get(int Id);  
  4.    Reservation Add(Reservation item);  
  5.    void Delete(int id);  
  6.    bool Update(Reservation item);  
  7. }  
The GetAll() method is of Enumerable type of Reservation since it expects a list of items as output. The Get(Id) method is of type Reservation and expects an item that matches the Id ed/specified. The Add(item) method is also a Reservation type since it adds a new item to the properties of the Reservation entity. The Delete method simply deletes/removes the item with Id ed. The Update method is a boolean type as if the model state is valid and if the update is successful it returns true.
  1. public class ReservationRepository : IReservationRepository {  
  2.    private List<Reservation> data = new List<reservation> {  
  3.       new Reservation {ReservationId = 1, Name = "ABC", Location = "London"},  
  4.       new Reservation {ReservationId = 2, Name = "XYZ", Location = "US"},  
  5.       new Reservation {ReservationId = 3, Name = "MNC", Location = "Paris"}  
  6.    };  
  7.   
  8.    private static ReservationRepository repo = new ReservationRepository();  
  9.    public static IReservationRepository getRepository(){  
  10.       return repo;  
  11.    }  
  12.    public IEnumerable GetAll(){  
  13.       return data;  
  14.    }  
  15.    public Reservation Get(int Id){  
  16.       var matchedItem = data.where(x => x.ReservationId == Id);  
  17.       return matchedItem.FirstOrDefault();  
  18.    }  
  19.   
  20.    public Reservation Add(Reservation item){  
  21.       item.ReservationId = data.Count() + 1;  
  22.       data.Add(item);  
  23.       return item;  
  24.    }  
  25.   
  26.    public void Delete(int is){  
  27.       Reservation item = Get(id);  
  28.       if(item != null){  
  29.       data.Delete(item);  
  30.       }  
  31.    }  
  32.   
  33.    public bool Update (Reservation item){  
  34.       Reservation Item = Get(item.ReservationId);  
  35.       if(Item != null){  
  36.          Item.Name = item.Name;  
  37.          Item.Location = item.Location;  
  38.          return true;  
  39.       }  
  40.       else{  
  41.          return false;  
  42.       }  
  43.    }  
  44. }  
  45.   
  46. public class ReservationController:ApiController{  
  47.    IReservationRepository repo = ReservationRepository.getRepository();  
  48.    public IEnumerable<Reservation> GetAllReservation()  
  49.    {  
  50.       return repo.GetAll();  
  51.    }  
  52.    public Reservation GetReservation(int id)  
  53.    {  
  54.       return repo.Get(id);  
  55.    }  
  56.    public Reservation PostReservation(Reservation item)  
  57.    {  
  58.       return repo.Add(item);  
  59.    }  
  60.   
  61.    public bool PutReservation(Reservation item)  
  62.    {  
  63.       return repo.Update(item);  
  64.    }  
  65.    public void deleteReservation(int id)  
  66.    {  
  67.       reo.Delete(id);  
  68.    }  
  69. }  
Let's start creating an Empty template MVC application and name it ReservationDemo. Since we have an empty MVC project then we only get Models, Controllers and Views as an empty folder :)

We add a model class as Reservation.cs into the Models folder. The Code snippet is as in the following:
  1. public class Reservation   
  2. {  
  3.    //Added the properties to the Reservation entity  
  4.    public int ReservationId {getset;} // Uniquely identifies each model object.  
  5.    public string Name {getset;}  
  6.    public string Location {getset;}  
  7. }  
Now we add an interface IReservationRepository.cs into the models folder again. The code snippet is as in the following.

Now let's add a Repository class to the Models itself that implements the interface IReservationRepository. The code snippet is as in the following. (Remember we are adding here into the models folder.)

The Home Controller is a normal controller created to return the main view page to our app. We just add a view to its Index()ActionResult method.

Creating API Controller

Add a controller, right-click on the controllers folder in the SolutionExplorer and select Add Controller from the popup menu. Change the controller name to ReservationController and select Empty API Controller from the Template drop-down menu. The Code snippet is as in the following.

The game after this is with the jQuery where the data results are bound on the AJAX calls.

Points of Interest

This is an interesting concept, using API that returns JSON results that can be used to bind data in the viewpage easily, using knockoutJs, BackboneJs.

History

I will soon post the data-bind using Knockout/Backbone Js. I hope this helps beginners like me.

Up Next
    Ebook Download
    View all
    Learn
    View all