Click here to Skip to main content
Click here to Skip to main content

Using Web Api in MVC4

, 21 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Steps to learn about Web APi controllers & their behaviour using a Demo.

Introduction

The Web Api (Application Programming Interface) feature is based on a special kind of controller to an MVC framework application, its normally as we do in MVC Smile | :) . An api controller distinguishes itself from the normal controllers by the following :-

  • Action methods return 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 ) Smile | :)

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

Background

We work using normal MVC4 framework, choosing an empty template. There is also a Web Api template but we cannot get to know the steps using that. Lets get into deeper following the steps 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. Lets start with a small Demo for better understanding. Lets go step by step :-

Creating the Model & Repository

public interface IReservationRepository{

IEnumerable<Reservation> GetAll(); 

Reservation Get(int Id);

Reservation Add(Reservation item);

 void Delete(int id);

bool Update(Reservation item);

}

The GetAll() method is of Enumerable type of Reservation as it expects a list of items as output. The Get(Id) method is of type Reservation that expects an item that matches the Id passed/specified. The Add(item) method is also a Reservation type as it adds a new item with the properties of the Reservation entity. The Delete method simply deletes/remove the item with Id passed. The Update method is boolean type as if model state is valid and update is successful its returns true.

public class ReservationRepository : IReservationRepository {
 
 private List<Reservation> data = new List<reservation> {
    
     new Reservation {ReservationId = 1, Name = "ABC", Location = "London"},
    
     new Reservation {ReservationId = 2, Name = "XYZ", Location = "US"},
    
     new Reservation {ReservationId = 3, Name = "MNC", Location = "Paris"}
     
        };

private static ReservationRepository repo = new ReservationRepository();

public static IReservationRepository getRepository(){

return repo;
}
public IEnumerable GetAll(){

return data;

}

public Reservation Get(int Id){

var matchedItem = data.where(x => x.ReservationId == Id);

return matchedItem.FirstOrDefault();

}

public Reservation Add(Reservation item){

item.ReservationId = data.Count() + 1;

data.Add(item);

return item;

}
public void Delete(int is){

Reservation item = Get(id);

if(item != null){
 
  data.Delete(item);
  }

}
public bool Update (Reservation item){

Reservation Item = Get(item.ReservationId);

if(Item != null){

  Item.Name = item.Name;

  Item.Location = item.Location;

  return true;
  }

else{

  return false;

}
}
}
public class ReservationController:ApiController{
IReservationRepository repo = ReservationRepository.getRepository();

public IEnumerable<Reservation> GetAllReservation()
{

  return repo.GetAll();

}

public Reservation GetReservation(int id)
{

  return repo.Get(id);

}

public Reservation PostReservation(Reservation item)
{

  return repo.Add(item);

}

public bool PutReservation(Reservation item)
{

  return repo.Update(item);

}

public void deleteReservation(int id)
{

  reo.Delete(id);

}

}
  1. Lets start creating an Empty template MVC application and name it ReservationDemo. Since we have empty MVC project then we only get Models, Controllers & Views as empty folder. Smile | :)
  2. We add a model class as Reservation.cs into the Models folder. The Code snippet goes below :
    public class Reservation 
    {
    //Added the properties to the Reservation entity
    
    public int ReservationId {get; set;}  // Uniquely identifies each model object.
    
    public string Name {get; set;}
    
    public string Location {get; set;}
    
    }
    
  3. Now we add an interface IReservationRepository.cs into the models folder again.The code snippet goes below:
  4. Now lets add a Repository class to the Models itself that implements the interface IReservationRepository. The code snippet goes below :- (Remember we are adding here into the models folder.)
  5. The Home Controller a normal controller is created to return the main view page to our app. We just add a view to its Index()ActionResult method.

    Creating API Controller

  6. Add a controller, right click on the contollers folder in the SolutionExplorer and select Add Controller from the popup menu. Change the controller name as ReservationController and select Empty Api Controller from the Template drop-down menu. The Code snippet goes as below:-

The game after this is with the Jquery where the data results are bind 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

Will post soon the data-bind using Knockout/Backbone Js. Hope this helps beginners like me.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Suraj Sahoo | Coding Passion
Software Developer (Junior) Mindfire Solutions
India India

I am the son of Mr. Debendra Nath Sahoo & Dr. Sanjulata Sahoo, felt worth mentioning them as they are the reason I am being able to key these words to the world.

I am currently a Software Developer at Mindfire Solutions,India.Working currently on ASP.NET MVC4 Web Applications.



I am passionate and enthusiastic to learn more about softwares and coding.Code Project is the best platform to feed me what i want.



I would love to know queries and questions from all of you specially beginners like me so that we could share some Code stuffs and make new recipes.Drop into suraj.0241@gmail.com.

My Own Blog

Suraj | Coding Passion

Achievements

I am Microsoft MVC4(70-486) certified.

 

Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralGood stuff PinmemberGaurav.Kumar.Arora27-Oct-14 10:14 
GeneralRe: Good stuff PinmemberSuraj Sahoo Mindfiresolutions27-Oct-14 18:10 
AnswerRe: Good stuff PinmemberGaurav.Kumar.Arora27-Oct-14 23:01 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun21-Jul-14 2:12 
GeneralRe: My vote of 5 PingroupSuraj Sahoo Mindfiresolutions21-Jul-14 2:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150123.1 | Last Updated 21 Jul 2014
Article Copyright 2014 by Suraj Sahoo | Coding Passion
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid