Implement ASP.Net Web API 2 in ASP.Net MVC 5

Introduction

Today, we'll learn how to access the Web API 2 in the ASP.NET MVC 5 application. Previously we have already learned how to work with the ASP.NET Web API 2.

Therefore in this article we'll create the Web API and access the Web API using MVC 5.

So, let's proceed with the following procedure:

  • Create ASP.NET Web API Application
  • Working with Web API Application
  • Working with MVC Controller
  • Adding MVC View

Prerequisites

To create this application, there are the following prerequisites:

  • Visual Studio 2013
  • ASP.NET MVC 5

Create ASP.NET Web API Application

In this section we'll create the ASP.NET Web Applicaiton using the Web API Project Template. So, start with the following procedure.

Step 1: Open Visual Studio and click on New Project.

Step 2: Select the ASP.NET Web Application and enter the name for the application.

Create ASP.Net Web Application

Step 3: Select Web API Project Template and tick the check box of MVC and click OK.

Web Api Project Template

Visual Studio automatically creates the Web API application using the MVC 5 based projects. When you run the application, the following is the home page of your application.

Web Api Application Home Page

You can also click on the Web API option to view the default API structure in the browser. The application Solution Explorer contains all the files and folders associated with the Web API application.

Wel Api Application Solution Explorer

Working with Web API Application

Now, we have created the Web API application that uses the MVC 5 based architecture. Now we'll proceed with the following procedure.

Adding Model

In this section, we'll add a class and an interface for creating the model. Use the procedure described below.

Step 1: In the Solution Explorer, right-click on the Models folder and click on Add to add class named Student.

Adding Class in Models Folder

Step 2: Replace the code with the following code:

  1. using System;  
  2.    
  3. namespace StudentApiApplication.Models  
  4. {  
  5.     public class Student  
  6.     {  
  7.         public int ID { getset; }  
  8.         public string Name { getset; }  
  9.         public string City { getset; }  
  10.         public string Course { getset; }  
  11.     }  
  12. }  

Step 3: Now add an interface to the models folder named IStudentRepository.

Adding Interface in Models Folder

Step 4: Replace the code with the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3.    
  4. namespace StudentApiApplication.Models  
  5. {  
  6.     interface IStudentRepository  
  7.     {  
  8.         IEnumerable<Student> GetAllStudents();  
  9.         Student AddStudent(Student student);  
  10.     }  
  11. }  

Step 5: Now we'll add a repository class in the models folder and after adding it, implement the interface in this class using the following code:

  1. public class StudentRepository : IStudentRepository  
  2. {  
  3. }  

Step 6: Now implement the interface using the following screenshot:

Implementing Interface in Class

Now modify the code with the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3.    
  4. namespace StudentApiApplication.Models  
  5. {  
  6.     public class StudentRepository : IStudentRepository  
  7.     {  
  8.         private List<Student> items = new List<Student>();  
  9.         private int next = 1;  
  10.         public StudentRepository()  
  11.         {  
  12.             AddStudent(new Student { ID = 1, Name = "Ashish", City = "New Delhi", Course = "B.Tech" });  
  13.             AddStudent(new Student { ID = 2, Name = "Nimit", City = "Noida", Course = "MCA" });  
  14.             AddStudent(new Student { ID = 3, Name = "Prawah", City = "Dehradun", Course = "B.Tech" });  
  15.             AddStudent(new Student { ID = 4, Name = "Sumit", City = "Nainital", Course = "MCA" });  
  16.         }  
  17.    
  18.         public IEnumerable<Student> GetAllStudents()  
  19.         {  
  20.             return items;  
  21.         }  
  22.    
  23.         public Student AddStudent(Student student)  
  24.         {  
  25.             if (items == null)  
  26.             {  
  27.                 throw new ArgumentNullException("student");  
  28.             }  
  29.    
  30.             student.ID = next++;  
  31.             items.Add(student);  
  32.             return student;  
  33.         }  
  34.     }  
  35. }  

Adding Controller

So far we have created the model, now we'll create the controller to use the model. Use the following procedure.

Step 1: In the Solution Explorer, right-click on the Controllers folder and click on Add to add the Controller.

Adding Controller in Web Api App

Step 2: In the Add Scaffold wizard, select the Web API 2 Empty Controller.

Adding Scaffold in Web APi

Step 3: Specify the name of the controller.

Adding Web API Controller

Step 4: Replace the code with the following code:

  1. using StudentApiApplication.Models;  
  2. using System.Collections.Generic;  
  3. using System.Web.Http;  
  4.    
  5. namespace StudentApiApplication.Controllers  
  6. {  
  7.     public class StudentsController : ApiController  
  8.     {  
  9.         static readonly IStudentRepository studentRepository = new StudentRepository();  
  10.    
  11.         public IEnumerable<Student> GetAll()  
  12.         {  
  13.             return studentRepository.GetAllStudents();  
  14.         }  
  15.     }  
  16. }  

Working with MVC Controller

In this section, we'll add an action method to the existing controller. You can also create a new controller. So now open the HomeController.cs in the Controllers folder and modify it with the following code:

  1. using System.Web.Mvc;  
  2.    
  3. namespace StudentApiApplication.Controllers  
  4. {  
  5.     public class HomeController : Controller  
  6.     {  
  7.         public ActionResult Index()  
  8.         {  
  9.             ViewBag.Title = "Home Page";  
  10.    
  11.             return View();  
  12.         }  
  13.    
  14.         public ActionResult Data()  
  15.         {  
  16.             ViewBag.Title = "Student Details";  
  17.             return View();  
  18.         }  
  19.     }  
  20. }  

In the code above, I've added an extra ActionResult method that is returning the View.

Adding MVC View

We'll add the MVC view here and work with the newly added view. Use the following procedure.

Step 1: In the HomeController class, right-click on the Data() and click on Add View.

Adding View

Step 2: Enter Data for view name and click on Add.

Add View Wizard

Step 3: Replace the code with the following code:

  1. @{  
  2.     ViewBag.Title = "Data";  
  3. }  
  4.    
  5. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  6. <script type="text/javascript">  
  7.     $(document).ready(function () {  
  8.         $.ajax({  
  9.             url: "http://localhost:44687/api/students",  
  10.             type: "Get",  
  11.             success: function (data) {  
  12.                 for (var i = 0; i < data.length; i++) {  
  13.                     $("<tr><td>" +  data[i].Name + "</td><td>" + data[i].Course + "</td><td>" + data[i].City + "</td></tr>").appendTo("#students");  
  14.                 }  
  15.             },  
  16.             error: function (msg) { alert(msg); }  
  17.         });  
  18.     });  
  19. </script>  
  20.    
  21. <h2>Index</h2>  
  22.    
  23. <div id="body">  
  24.     <section class="content-wrapper main-content">  
  25.         <table id="students" class="table">  
  26.             <thead>  
  27.                 <tr>  
  28.                     <th>@Html.DisplayName("Name")</th>  
  29.    
  30.                     <th>@Html.DisplayName("Course")</th>  
  31.    
  32.                     <th>@Html.DisplayName("City")</th>  
  33.                 </tr>  
  34.             </thead>  
  35.         </table>  
  36.     </section>  
  37. </div>  

 

In the code above, I've used the jQuery to call the Web API.

Step 4: Open the Views/Shared/_Layout.cshtml page and add an ActionLink to redirect to your View.

  1. <li>@Html.ActionLink("Student""Data""Home", new { area = "" }, null)</li>  

 

Step 5: Now run the application. In the Home Page, click on the Student link.

Calling Controller in MVC 5

You can see in the following screenshot that, the data is coming by the Web API.

Calling Web API in MVC 5

Summary

This article described how to create the Web API and access that Web API in the ASP.NET MVC 5. We'll show the CRUD operations in further articles. Thanks for reading.


Similar Articles