CRUD Operation using Web API and MVC4

Niladri.Biswas
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 29986 red flag
Rating: 4 out of 5  
 2 vote(s)

In this article we will perform a basic CRUD operation using Web API and MVC4


 Download source code for CRUD Operation using Web API and MVC4

Introduction

In this article we will perform a basic CRUD operation using Web API and MVC4

Straight to Experiment

Fire up visual studio and choose "ASP.NET MVC 4 Web Application"

Next choose "Web API" and let the view engine be "Razor".Click "OK"

Add an Employee Model (Employee.cs) in the Models Folder

public class Employee
{       
	public int id { get; set; }
	public string name { get; set; }
	public string gender { get; set; }
	public int age { get; set; }
	public int salary { get; set; }
}

Add an Interface IEmployeeRepository.cs as under

interface IEmployeeRepository
{
	IEnumerable<Employee> GetAll();
	Employee Get(int id);
	Employee Add(Employee employee);        
	Employee Update(Employee employee);
	IEnumerable<Employee> Delete(int id);
}

Add a concrete EmployeeRepository.cs as under

public class EmployeeRepository : IEmployeeRepository
{
	private List<Employee> employees = new List<Employee>();
	private int _nextId = 1;

	public EmployeeRepository()
	{
		Add(new Employee { id = 1, name = "Michale Sharma", gender = "Male", age = 25, salary=10000 });
		Add(new Employee { id = 2, name = "Sunil Das", gender = "Male", age = 24, salary =5000 });
		Add(new Employee { id = 3, name = "Robin Pandey", gender = "Male", age = 35,salary =45000 });
		Add(new Employee { id = 4, name = "Mona Singh", gender = "Female", age = 27, salary=12000 });
	}

	public IEnumerable<Employee> GetAll()
	{
		return employees;
	}

	public Employee Get(int id)
	{
		return employees.Find(e => e.id == id);
	}

	public Employee Add(Employee employee)
	{
		if (employee == null)
		{
			throw new ArgumentNullException("Employee");
		}
		employee.id= _nextId++;
		employees.Add(employee);
		return employee;
	}      

	public Employee Update(Employee employee)
	{
		if (employee == null)
		{
			throw new ArgumentNullException("Employee");
		}
		int index = employees.FindIndex(e => e.id == employee.id);            
		employees.RemoveAt(index);
		employees.Add(employee);
		return employee;
	}

	public IEnumerable<Employee> Delete(int id)
	{
		employees.RemoveAll(e => e.id == id);
		return employees;
	}
}

Now let us design the Index.chtml inside the "Home" view

<table border="1">

    <tr>
        <td>
            <h1 style="color: green">Get All Employees </h1>
            <button id="btnAllEmployee" onclick="GetAllEmployees();return false;">Get All Employees</button><br>
            <div id="divDisplayAllEmployees"></div>              
        </td>
        <td>
            <h1 style="color: green">Get Single Employee Record</h1>
            Enter EmployeeId:<input id="txtSingleEmployeeId" type="text" />
            <button id="btnSingleEmployee" onclick="GetSingleEmployee();return false;">Get Single Employee Record</button><br>
            <div id="divDisplaySingleEmployee"></div>             
        </td>
    </tr>
    <tr>
        <td>
            <h1 style="color: green">Add/Update Employee</h1>
                <table border="1">
                    <tr>
                        <td>Employee Id</td>
                        <td><input id="txtEmployeeId" type="text" /></td>
                    </tr>
                    <tr>
                        <td>Employee Name</td>
                        <td><input id="txtEmployeeName" type="text" /></td>
                    </tr>
                    <tr>
                        <td>Employee Gender</td>
                        <td>
                                <select id="optGender">
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                </select>
                        </td>
                    </tr>
                    <tr>
                        <td>Employee Age</td>
                        <td><input id="txtEmployeeAge" type="text" /></td>
                    </tr>
                    <tr>
                        <td>Employee Salary</td>
                        <td><input id="txtEmployeeSalary" type="text" /></td>
                    </tr>
                    <tr>
                        <td><button id="btnPostEmployee" onclick="AddEmployee()">Add New Employee</button></td>
                        <td><button id="btnPutEmployee" onclick="UpdateEmployee()">Update Employee</button></td>
                    </tr>
                </table> 
        </td>

        <td>
            <h1 style="color: green">Delete Employee</h1>
                Enter EmployeeId:<input id="txtEmpId" type="text" />
                <button id="btnDeleteEmployee" onclick="DeleteEmployee();return false;">Delete Employee</button><br>             
        </td>
    </tr>
</table>

Next make a EmployeeController.cs that inherits from the "ApiController" class.And add the below method.

using System.Collections.Generic;
using System.Web.Http;
using MvcApplication1.Models;

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

        //Get all employees
                                        
        //api/employee

        public IEnumerable<Employee> GetAllEmployees()
        {
            return employeeRepository.GetAll();
        }

    }
}

Correspondingly add the below javascript function

function GetAllEmployees() {
    jQuery.support.cors = true;
    $.ajax({
        url: 'http://localhost:41207/api/employee',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            WriteResponses(data);
        },
        error: function (x, y, z) {
            alert(x + '\n' + y + '\n' + z);
        }
    });

    //Displays in a Table
    function WriteResponses(employees) {
        var strResult = "<table><th>Id</th><th>Name</th><th>Gender</th><th>Age</th><th>Salary</th>";
        $.each(employees, function (index, employee) {
            strResult += "<tr><td>" + employee.id + "</td><td> " + employee.name + "</td><td>" + employee.gender + "</td><td>" + employee.age + "</td><td>" + employee.salary + "</td></tr>";
        });
        strResult += "</table>";
        $("#divDisplayAllEmployees").html(strResult);
    }
}

We are performing the Ajax call and from the result set we obtain, we are looping through every record to display it.

Next we will try to get the record for a single employee.

For that add the below function in the EmployeeController

// GET a particular employee

//api/employee/2
public Employee GetEmployee(int id)
{
	return employeeRepository.Get(id); ;

}

Correspondingly add the below javascript function

function GetSingleEmployee() {
    jQuery.support.cors = true;
    var empId = $('#txtSingleEmployeeId').val();

    $.ajax({
        url: 'http://localhost:41207/api/employee/' + empId,
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            WriteResponseForSingleEmployee(data);
        },
        error: function (x, y, z) {
            alert('The Employee not found in the List for the given ID');
        }
    });

    function WriteResponseForSingleEmployee(employee) {       
        var strResult = "<table><th>Id</th><th>Name</th><th>Gender</th><th>Age</th><th>Salary</th>";
        strResult += "<tr><td>" + employee.id + "</td><td> " + employee.name + "</td><td>" + employee.gender + "</td><td>" + employee.age + "</td><td>" + employee.salary + "</td></tr>";
        strResult += "</table>";
        $("#divDisplaySingleEmployee").html(strResult);
       
    }
}

Next we will try to add an employee.

For that add the below function in the EmployeeController

public Employee PostEmployee(Employee employee)
{
	return employeeRepository.Add(employee);
}

Correspondingly add the below javascript function

function AddEmployee() {
    var employee = {        
        id: $('#txtEmployeeId').val(),
        name: $('#txtEmployeeName').val(),
        gender: $('#optGender').val(),
        age: $('#txtEmployeeAge').val(),
        salary: $('#txtEmployeeSalary').val()
    };

    $.ajax({
        url: 'http://localhost:41207/api/employee/',
        type: 'POST',
        data: JSON.stringify(employee),
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            alert('Employee added Successfully');
            GetAllEmployees();
        },
        error: function () {
            alert('Employee not Added');
        }
    });
}

Next we will try to update an employee.

For that add the below function in the EmployeeController

public Employee PutEmployee(int id, Employee employee)
{
	employee.id = id;
	return employeeRepository.Update(employee);
	
}

Correspondingly add the below javascript function

function UpdateEmployee() {
    var employee = {
        id: $('#txtEmployeeId').val(),
        name: $('#txtEmployeeName').val(),
        gender: $('#optGender').val(),
        age: $('#txtEmployeeAge').val(),
        salary: $('#txtEmployeeSalary').val()
    };

    $.ajax({
        url: 'http://localhost:41207/api/employee/' + $('#txtEmployeeId').val(),
        type: 'PUT',
        data: JSON.stringify(employee),
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            alert('Employee updated Successfully');
            GetAllEmployees();
        },
        error: function () {
            alert('Employee could not be updated');
        }
    });
}

Next we will try to delete an employee.

For that add the below function in the EmployeeController

public IEnumerable<Employee> DeleteEmployee(int id)
{
	return employeeRepository.Delete(id);           

}

Correspondingly add the below javascript function

function DeleteEmployee() {

    jQuery.support.cors = true;
    var id = $('#txtEmpId').val()

    $.ajax({
        url: 'http://localhost:41207/api/employee/' + id,
        type: 'DELETE',
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            WriteResponsesForAllEmployees(data);
        },
        error: function (x, y, z) {
            alert(x + '\n' + y + '\n' + z);
        }
    });
}

Conclusion

So our journey end here.Hope this will be useful.Thanks for reading.Zipped file is attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Posted by: Chakravarthi on: 7/29/2013 | Points: 25
Useful
Thanks
Posted by: Poojawadekar on: 7/16/2016 | Points: 25
Nice Post. but I want to add data in database through emailer. and your code is not working.

Login to post response

Comment using Facebook(Author doesn't get notification)