ASP.NET Web API 2 in MVC 5 Using C# with Example

watch_later 2/28/2019

Introduction


This article gives an explanation about how to create and access the Web API 2 in the ASP.NET MVC 5 application using C# and bootstrap with Example. Here I'll also show you how to create the step by step Web API 2 in ASP.Net MVC 5 Using C# and bootstrap with the simple example, In this tutorial, you will use ASP.NET Web API 2 to create a web API and that returns a list of employees.


Many of developers/programmers those who work with ASP.Net, MVC, Java, PHP, Python will have at least heard talk about the Web API. Even if any developers/programmers know on a basic level what Web API do, they are not always certain when to use Web API and how to write the code to use Web API etc. So, in this article, I am going to explain how to create web API in asp.net MVC applications and how to use Web API in a web application with an example.


Requirement


1) Create ASP.NET MVC Web API Application using Bootstrap.
2) Get a list of All Employee.
3) Search Employee Based on Employee ID and Display on Screen.

Implementation


So, let's start with and simple example of the employee where we will retrieve all the information of employee using WEB API.

Step 1: Open Your Visual Studio 2013 or higher versions.

Step 2: Goto File menu and Create New Project same as shown below.

Create MVC Projects

Step 3: Now you can see following popup window on your screen you have to follow some steps as shown in the screen below.

Asp-Net Web Application

Step 4: Now, When you click on OK button you can see one another popup window will appear on your screen same as shown below, where you have to select WEB API and click OK.

Asp.net mvc web api

Step 5: Finally, your WEB API project has been created and your project structure look likes same as shown below.

Asp.net MVC project structure

Step 6: Now, if you can see then there is two default created controllers are available where you have to open your controller file "ValuesController.cs" and need to do following modification in your controller.

values controller

Here, I will change my Controller Name ValueController to EmployeeController which is derived from ApiController.
public class EmployeeController : ApiController
Now, I will create a simple class and defines some basic properties of employees such as ID, Name, Designation, Salary and etc.
public class Employee
{
    public int EmpId { getset; }
    public string EmployeeName { getset; }
    public string Designation { getset; }
    public decimal Salary { getset; }
}
Then I will define a simple array and store some sample data of employees on it.
Employee[] Employees = new Employee[]{
    new Employee {EmpId=1,EmployeeName="Nikunj Satasiya", Designation="Software Engineer", Salary=78000},
    new Employee {EmpId=2,EmployeeName="Hiren Dobariya", Designation="Software Engineer", Salary=72000},
    new Employee {EmpId=3,EmployeeName="Vivek Ghadiya", Designation="Software Engineer", Salary=75000},
    new Employee {EmpId=4,EmployeeName="Pratik Pansuriya", Designation="Software Engineer", Salary=55000},
    new Employee {EmpId=5,EmployeeName="Nikunj Ladani", Designation="Software Engineer", Salary=42000},
    new Employee {EmpId=6,EmployeeName="Sarah Demola", Designation="Software Engineer", Salary=90000}
};
Now, I will write a method which is returns all the details of Employee for Every Employee.
public IEnumerable<Employee> GetAllEmployees()
{
    return Employees;
}
Then after I will write a second method which returns details of the single employee based on employee id.
public IHttpActionResult Get(int Id)
{
    var Employee = Employees.FirstOrDefault((e) => e.EmpId == Id);
    if (Employee == null)
    {
        return NotFound();
    }
    return Ok(Employee);
}
Step 7: Now, It's Time to add simple HTML form in our application and for that, you have to follow some steps described in the screen below.

Add New Item

Step 8: Now, You have to write the following code in the HTML file.

Add New HTML Web Page

HTML Markup

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Codingvila Web API</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <link rel="stylesheet" type="text/css" href="Content/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="Content/bootstrap.min.css"/>
</head>
<body class="container">
    <div>
        <h2>All Employees</h2>
        <ul id="Employees" />
    </div>
    <div>
        <h2>Search by Employee ID</h2>
        <input type="text" style=" width:50%" class="form-control" id="EmpId" size="5" />
        <br />
        <input type="button"  class="btn btn-primary" value="Search" onclick="FindEmployee();" />
        <br />
        <br />
        <p id="Employee" style=" width:50%" />
    </div>
 
 
    <script>
        var uri = 'api/employee';
 
        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON(uri)
                .done(function (data) {
                    // On success, 'data' contains a list of Employee.
                    $.each(data, function (key, Data) {
                        // Add a list Data for the Employee.
                        $('<div>', { text: formatData(Data) }).appendTo($('#Employees'));
                        });
                });
        });
 
        function formatData(Data) {
            return 'Name :-' + Data.EmployeeName + ', Designation :- ' + Data.Designation + ', Salary :- ' + Data.Salary;
        }
 
        function FindEmployee() {
            var id = $('#EmpId').val();
            $.getJSON(uri + '/' + id)
                .done(function (data) {
                    $('#Employee').text(formatData(data));
                    $('#Employee').removeClass('alert alert-danger');
                    $('#Employee').addClass('alert alert-success');
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#Employee').text('Error: ' + err);
                    $('#Employee').addClass('alert alert-danger');
                    $('#Employee').removeClass('alert alert-success');
                });
        }
    </script>
</body>
</html>
Step 9:  Now you have to run your application and for that, you can press F5 and your web page look like same as shown below.

ASP.NET WEB API 2

Search Employee By Employee ID



Step 10: To View the HTTP Request and Response you have to press F12, and then click on the Network tab and then press start capturing red icon and now go back to the web page and reload the web page or press F5 to reload the web page and you can see the HTTP Request and Response same as shown below.
HTTP-Request-response-WEB-API

HTTP-Request-response-WEB-API-json
Headers-WEB-API
get-by-ID-Headers-WEB-API

Summary


This article gives an explanation about how to create and access the Web API 2 in the ASP.NET MVC 5 application using C#.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon