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.
Step 3: Select Web API Project Template and tick the check box of MVC and click OK.
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.
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.
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.
Step 2: Replace the code with the following code:
- using System;
-
- namespace StudentApiApplication.Models
- {
- public class Student
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string City { get; set; }
- public string Course { get; set; }
- }
- }
Step 3: Now add an interface to the models folder named IStudentRepository.
Step 4: Replace the code with the following code:
- using System;
- using System.Collections.Generic;
-
- namespace StudentApiApplication.Models
- {
- interface IStudentRepository
- {
- IEnumerable<Student> GetAllStudents();
- Student AddStudent(Student student);
- }
- }
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:
- public class StudentRepository : IStudentRepository
- {
- }
Step 6: Now implement the interface using the following screenshot:
Now modify the code with the following code:
- using System;
- using System.Collections.Generic;
-
- namespace StudentApiApplication.Models
- {
- public class StudentRepository : IStudentRepository
- {
- private List<Student> items = new List<Student>();
- private int next = 1;
- public StudentRepository()
- {
- AddStudent(new Student { ID = 1, Name = "Ashish", City = "New Delhi", Course = "B.Tech" });
- AddStudent(new Student { ID = 2, Name = "Nimit", City = "Noida", Course = "MCA" });
- AddStudent(new Student { ID = 3, Name = "Prawah", City = "Dehradun", Course = "B.Tech" });
- AddStudent(new Student { ID = 4, Name = "Sumit", City = "Nainital", Course = "MCA" });
- }
-
- public IEnumerable<Student> GetAllStudents()
- {
- return items;
- }
-
- public Student AddStudent(Student student)
- {
- if (items == null)
- {
- throw new ArgumentNullException("student");
- }
-
- student.ID = next++;
- items.Add(student);
- return student;
- }
- }
- }
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.
Step 2: In the Add Scaffold wizard, select the Web API 2 Empty Controller.
Step 3: Specify the name of the controller.
Step 4: Replace the code with the following code:
- using StudentApiApplication.Models;
- using System.Collections.Generic;
- using System.Web.Http;
-
- namespace StudentApiApplication.Controllers
- {
- public class StudentsController : ApiController
- {
- static readonly IStudentRepository studentRepository = new StudentRepository();
-
- public IEnumerable<Student> GetAll()
- {
- return studentRepository.GetAllStudents();
- }
- }
- }
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:
- using System.Web.Mvc;
-
- namespace StudentApiApplication.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- ViewBag.Title = "Home Page";
-
- return View();
- }
-
- public ActionResult Data()
- {
- ViewBag.Title = "Student Details";
- return View();
- }
- }
- }
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.
Step 2: Enter Data for view name and click on Add.
Step 3: Replace the code with the following code:
- @{
- ViewBag.Title = "Data";
- }
-
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- $.ajax({
- url: "http://localhost:44687/api/students",
- type: "Get",
- success: function (data) {
- for (var i = 0; i < data.length; i++) {
- $("<tr><td>" + data[i].Name + "</td><td>" + data[i].Course + "</td><td>" + data[i].City + "</td></tr>").appendTo("#students");
- }
- },
- error: function (msg) { alert(msg); }
- });
- });
- </script>
-
- <h2>Index</h2>
-
- <div id="body">
- <section class="content-wrapper main-content">
- <table id="students" class="table">
- <thead>
- <tr>
- <th>@Html.DisplayName("Name")</th>
-
- <th>@Html.DisplayName("Course")</th>
-
- <th>@Html.DisplayName("City")</th>
- </tr>
- </thead>
- </table>
- </section>
- </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.
- <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.
You can see in the following screenshot that, the data is coming by the Web API.
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.