ASP.NET Web API CRUD Operations

What is the ASP.NET Web API? The ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. The ASP.NET Web API is an ideal platform for building REST applications on the .NET Framework.

Getting Started

First of all, you need to install the .Net framework 4.5 and MVC 4 if you are using Visual Studio 2010. Now create a new project in Visual Studio 2010 select ASP.NET MVC 4 Web Application and select Web API template and click OK.

Now add a new class in the Models "Employee".

namespace WebAPISample1.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Designation { get; set; }
        public string Address { get; set; }
    }
}

Now add one more class "EmployeeRepository".

namespace WebAPISample1.Models
{
    public class EmployeeRepository : IEmployeeRepository
    {
        private List<Employee> _employee = new List<Employee>();
        private int _nextId = 1;

        public EmployeeRepository()
        {
            this.Add(new Employee() { Name = "Raj Beniwal", Designation = "Asst. Project Manager", Address= "Noida" });
            this.Add(new Employee() { Name = "Dev Malhotra", Designation = "Tech Lead", Address = "Banglore" });
            this.Add(new Employee() { Name = "Neelesh Arora", Designation = "System Analyst", Address= "Pune"});
            this.Add(new Employee() { Name = "Samy Verma", Designation = "Project Manager", Address = "Washingtom DC" });
            this.Add(new Employee() { Name = "Ravinder Malik", Designation = "Team Lead", Address = "Gurgaon" });
        }

        public IQueryable<Employee> GetAll()
        {
            return _employee.AsQueryable();
        }

        public Employee Get(int id)
        {
            return _employee.Find(c => c.Id == id);
        }

        public Employee Add(Employee employee)
        {
            employee.Id = _nextId++;
            _employee.Add(employee);
            return employee;
        }

        public void Remove(int id)
        {
            Employee employee = _employee.Find(c => c.Id == id);
            _employee.Remove(employee);
        }

        public bool Update(Employee employee)
        {
            int index = _employee.FindIndex(c => c.Id == employee.Id);
            if (index == -1)
            {
                return false;
            }
            _employee.RemoveAt(index);
            _employee.Add(employee);
            return true;
        }
    }
}

Now add one interface "IEmployeeRepository".

namespace WebAPISample1.Models
{
    public interface IEmployeeRepository
    {
        IQueryable<Employee> GetAll();
        Employee Get(int id);
        Employee Add(Employee item);
        void Remove(int id);
        bool Update(Employee item);
    }
}

Now add a new controller "EmployeeController" and call all model functions to expose data.

EmployeeController

Image 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPISample1.Models;

namespace WebAPISample1.Controllers
{
    public class EmployeeController : ApiController
    {
        static readonly IEmployeeRepository repository = new EmployeeRepository();

        public IEnumerable<Employee> GetAllEmployee()
        {
            return repository.GetAll();
        }

        public Employee GetEmployee(int id)
        {
            Employee item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            return item;
        }

        public IEnumerable<Employee> GetEmployeeByName(string name)
        {
            return repository.GetAll().Where(
                p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        public HttpResponseMessage PostEmployee(Employee item)
        {
            item = repository.Add(item);
            var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, item);
            string uri = Url.Link("DefaultApi", new { id = item.Id });
            response.Headers.Location = new Uri(uri);
            return response;
        }

        public void PutEmployee(int id, Employee employee)
        {
            employee.Id = id;
            if (!repository.Update(employee))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }

        public HttpResponseMessage DeleteEmployee(int id)
        {
            repository.Remove(id);
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
}

We are done here with models and controller work. Now you will see API data like this.

http://localhost:56065/api/employee.

Let's load the data into the view now.

Add a new view in the Views/Home folder.

@{
    ViewBag.Title = "Employee List";
}
@section scripts {
    <style type="text/css">
        table {
            border: 1px solid #000;
            border-collapse: collapse;
            color: #666666;
            min-width: 200px;
        }

        tr {
            border: 1px solid #000;
            line-height: 25px;
        }

        th {
            background-color: #B1C3CC;
            color: #000;
            font-size: 13px;
            text-align: left;
        }

        th,
        td {
            padding-left: 5px;
        }
    </style>
    <script src="@Url.Content("~/Scripts/jquery-1.6.2.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout-2.0.0.debug.js")" type="text/javascript"></script>
    <script type="text/javascript">
        function clearStatus() {
            $('#status').html('');
        }

        var detailModel = function () {
            this.Name = ko.observable();
            this.Designation = ko.observable();
            this.Address = ko.observable();
        }

        var API_URL = "api/employee/";
        var viewModel = new detailModel();

        //This function used to insert new employee record
        function add() {
            clearStatus();
            var employee = ko.toJS(viewModel);
            var json = JSON.stringify(employee);

            $.ajax({
                url: API_URL,
                cache: false,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: json,
                statusCode: {
                    201 /*Created*/: function (data) {
                        self.employees.push(data);
                    }
                }
            });
        }

        //This function used to find employee by id
        function find() {
            clearStatus();
            var id = $('#employeeId').val();
            $.getJSON(API_URL + id,
                function (data) {
                    viewModel.Name(data.Name);
                    viewModel.Designation(data.Designation);
                    viewModel.Address(data.Address);
                })
                .fail(
                    function (xhr, textStatus, err) {
                        $('#status').html('Error: ' + err);
                    });
        }

        //This function used to updated employee based on id
        function update() {
            clearStatus();
            var id = $('#employeeId').val();
            var employees = ko.toJS(viewModel);
            var json = JSON.stringify(employees);
            $.ajax({
                url: API_URL + id,
                cache: false,
                type: 'PUT',
                contentType: 'application/json; charset=utf-8',
                data: json,
                success: function () { $.getJSON(API_URL, self.employees.update); }
            })
                .fail(
                    function (xhr, textStatus, err) {
                        $('#status').html('Error: ' + err);
                    });
        }

        $(document).ready(function () {
            self.employees = ko.observableArray();
            self.employees.update = function (data) {
                var c = self.employees;
                c.removeAll();
                c.push.apply(c, data);
                // Sort by ID
                c.sort(
                    function (left, right) { return left.Id - right.Id }
                );
            };
            ko.applyBindings(self.employees, document.getElementById('employees'));
            ko.applyBindings(viewModel, document.getElementById('detail'));
            $.getJSON(API_URL, self.employees.update);
        });
    </script>
}
<p id="body">
    <section class="content-wrapper main-content">
        <h3>Employees</h3>
        <table id="employees">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Designation</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: employees">
                <tr>
                    <td data-bind="text: Id"></td>
                    <td data-bind="text: Name"></td>
                    <td data-bind="text: Designation"></td>
                    <td data-bind="text: Address"></td>
                </tr>
            </tbody>
        </table>
    </section>
    <section id="detail" class="content-wrapper">
        <h3>View Employee</h3>
        <p>
            <label for="employeeId">ID</label>
            <input type="text" title="ID" id="employeeId" size="5" />
            <input type="button" value="Get" onclick="find();" />
        </p>
        <p>
            <label for="name">Name</label>
            <input data-bind="value: Name" type="text" title="Name" id="name" />
        </p>
        <p>
            <label for="designation">Designation</label>
            <input data-bind="value: Designation" type="text" title="Designation" id="designation" />
        </p>
        <p>
            <label for="address">Address</label>
            <input data-bind="value: Address" type="text" title="Address" id="address" />
        </p>
        <p>
            <input type="button" value="Update" onclick="update();" />
            <input type="button" value="Add New" onclick="add();" />
        </p>
        <p>
            <p id="status"></p>
        </p>
    </section>
</p>

Compile the application to see the result.

Compile the application

Image 2

Enter the name, designation, and address to add a new record, and click Add New.

Add New

Image 3

To update an existing record, enter the record type ID click Get edit the data, and click Update.

 Record type ID

Image 4


Similar Articles