CRUD Operations using ASP.NET Web API.


This Tutorial will explain how to implement crud operations using ASP.NET Web API.

Open Visual Studio 2012. Go to create new project tab. Select “Asp.Net MVC 4 Web Application.” Then select Web API from Project Template.

using ASP.NET Web API Crud operation are performed by

GET – To Get data from database
POST – To Insert data into database
PUT – To Update data into database
DELETE – To delete data in database

Create an Employee class in Model folder. And write the below code in the file.

public class Employee
{
    [Display(Name = "Employee ID")]
    public string EmployeeID { get; set; }
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Date of Birth")]
    public string DOB { get; set; }

    public string Gender { get; set; }
    public string Nationality { get; set; }
    public string Language { get; set; }
    public string Address { get; set; }
}


Create an EmployeeController Controller file in Controller folder. And write the below code in the file.

public class EmployeeController : ApiController
{
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }
    public void Post(Employee Employee)
    {
        EmployeeDAL.AddEmployee(Employee);
    }
    public void Put(Employee Employee, string id)
    {
        EmployeeDAL.UpdateEmployee(Employee, id);
    }
    public void Delete(string id)
    {
        EmployeeDAL.RemoveEmployee(id);
    }
}


Create a EmployeeDAL file in Model folder for DataBase Operations.

 public class EmployeeDAL
    {
        private static List<Employee> employees;

        public static List<Employee> GetAllEmployees()
        {            
            try
            {
               // Code to fetch data from database
               // create employee list and return
               // return employees;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        public static Employee GetEmployee(string employeeID)
        {           
            try
            {
                // Code to fetch data from database based on employeeID
                // create list and return                           
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void RemoveEmployee(string employeeID)
        {           
            try
            {
                // Code to delete record from database based on employeeID                              
            }
            catch (SqlException ex)
            {
                throw ex;
            }           
        }
        public static void AddEmployee(Employee employee)
        {            
            try
            {    
                 // Code to Insert employee data into database         
            }
            catch (SqlException ex)
            {
                throw ex;
            }            
        }
        public static void UpdateEmployee(Employee employee, string id)
        {           
            try
            {
                 // Code to update employee data into database             
            }
            catch (SqlException ex)
            {
                throw ex;
            }            
        }
    }


Open Index.cshtml file in View folder. And replace body code with the code below.

<div id="body">
    <section class="featured">
        <div class="content-wrapper">
        </div>
        <div class="content-wrapper main-content clear-fix">
            <h2>Search</h2>
            @model WebApiPart1.Models.Employee
            @using (Html.BeginForm())
            {
                @Html.ValidationSummary(true)
                <fieldset>
                    <legend>Employee Search</legend>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.EmployeeID)
                    </div>
                    <div class="editor-field">
                        @Html.TextBox("SearchEmployee")
                        @Html.ValidationMessageFor(model => model.EmployeeID)
                    </div>
                    <p>
                        <input type="submit" value="Search" onclick="SearchEmployeeById(); return false;" />
                        <input type="submit" value="Get ALL" onclick="GelAllEmployees(); return false;" />
                    </p>
                </fieldset>
                <h2>Employee List</h2>
                <table border="1" id="employees">
                    <thead>
                        <tr>
                            <th><b>Employee ID</b></th>
                            <th><b>First Name</b></th>
                            <th><b>Last Name</b></th>
                            <th><b>DOB</b></th>
                            <th><b>Gender</b></th>
                            <th><b>Nationality</b></th>
                            <th><b>Language</b></th>
                            <th><b>Address</b></th>
                            <th><b>Edit</b></th>
                            <th><b>Delete</b></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <h2>Create</h2>
                <fieldset>
                    <legend>Employee</legend>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.EmployeeID)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.EmployeeID)
                        @Html.ValidationMessageFor(model => model.EmployeeID)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.FirstName)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.FirstName)
                        @Html.ValidationMessageFor(model => model.FirstName)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.LastName)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.LastName)
                        @Html.ValidationMessageFor(model => model.LastName)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.DOB)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.DOB)
                        @Html.ValidationMessageFor(model => model.DOB)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Gender)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Gender)
                        @Html.ValidationMessageFor(model => model.Gender)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Nationality)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Nationality)
                        @Html.ValidationMessageFor(model => model.Nationality)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Language)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Language)
                        @Html.ValidationMessageFor(model => model.Language)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Address)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Address)
                        @Html.ValidationMessageFor(model => model.Address)
                    </div>
                    <p>
                        <input type="submit" id="AddUpdate" name="AddUpdate" value="Create" onclick="ADDUpdate(); return false;" />
                        <input type="submit" id="Clear" name="Clear" value="Clear" onclick="ClearForm(); return false;" />
                    </p>
                </fieldset>
            }
        </div>
    </section>
</div>

Asp.Net Web API

Asp.Net Web API

Get ALL Employee List using GET method.

 function GelAllEmployees() {
 $.ajax({
 type: "GET",
 url: "api/Employee",
 contentType: "json",
 dataType: "json",
 success: function (data) {
 $('#employees tbody tr').empty();
 $.each(data, function (key, value) {
 //stringify
 var jsonData = JSON.stringify(value);
 //Parse JSON
 var objData = $.parseJSON(jsonData);
 var id = objData.EmployeeID;
 var fname = objData.FirstName;
 var lname = objData.LastName;
 var dob = objData.DOB;
 var Gender = objData.Gender;
 var Nationality = objData.Nationality;
 var Language = objData.Language;
 var Address = objData.Address;
 $('
<tr>
<td>' + id + '</td>
<td>' + fname +
 '</td>
<td>' + lname + '</td>
<td>' + dob + '</td>
<td>' + Gender + '</td>
<td>' + Nationality + '</td>
<td>' + Language +
 '</td>
<td>' + Address + '</td>
<td><a onclick="GetEmployeeById(id); return false;" id="' + id + '" >Edit</a></td>
<td><a onclick="DeleteEmployee(id);" id="' + id + '" >Delete</a></td>
</tr>

').appendTo('#employees tbody');
 });
 },
 error: function (xhr) {
 alert(xhr.responseText);
 }
 });
 };


Get Employee by ID

 function GetEmployeeById(EmployeeID) {
    var employeeData = {
        "EmployeeID": EmployeeID
    };
    $.ajax({
        type: "GET",
        url: "api/Employee/" + employeeData.EmployeeID,
        contentType: "json",
        dataType: "json",
        success: function (data) {
            //stringify
            var jsonData = JSON.stringify(data);
            //Parse JSON
            var objData = $.parseJSON(jsonData);
            if (objData == null) {
                return;
            }
            $('#AddUpdate').val("Update");            
            $('#EmployeeID').val(objData.EmployeeID);
            $('#FirstName').val(objData.FirstName);
            $('#LastName').val(objData.LastName);
            $('#DOB').val(objData.DOB);
            $('#Gender').val(objData.Gender);
            $('#Nationality').val(objData.Nationality);
            $('#Language').val(objData.Language);
            $('#Address').val(objData.Address);
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });
}       


Search Employee by Employee ID

 function SearchEmployeeById() {
            var employeeData = {
                "EmployeeID": $('#SearchEmployee').val()
            };
            if (employeeData.EmployeeID == "") {
                return false;
            }
            $.ajax({
                type: "GET",
                url: "api/Employee/" + employeeData.EmployeeID,
                contentType: "json",
                dataType: "json",
                success: function (data) {
                    //stringify
                    $('#employees tbody tr').empty();
                    var jsonData = JSON.stringify(data);
                    //Parse JSON
                    var objData = $.parseJSON(jsonData);
                    if (objData == null) {
                        return;
                    }
                    var id = objData.EmployeeID;
                    var fname = objData.FirstName;
                    var lname = objData.LastName;
                    var dob = objData.DOB;
                    var Gender = objData.Gender;
                    var Nationality = objData.Nationality;
                    var Language = objData.Language;
                    var Address = objData.Address;
                    $('
<tr>
<td>' + id + '</td>
<td>' + fname +
                    '</td>
<td>' + lname + '</td>
<td>' + dob + '</td>
<td>' + Gender + '</td>
<td>' + Nationality + '</td>
<td>' + Language +
                    '</td>
<td>' + Address + '</td>
<td><a onclick="GetEmployeeById(id); return false;" id="' + id + '" >Edit</a></td>
<td><a onclick="DeleteEmployee(id); return false;" id="' + id + '" >Delete</a></td>
</tr>

').appendTo('#employees tbody');

                },
                error: function (xhr) {
                    alert(xhr.responseText);

                }
            });
        }


Add New Employee

 function AddNewEmployee() {
            var employeeData = {
                "EmployeeID": $('#EmployeeID').val(),
                "FirstName": $('#FirstName').val(),
                "LastName": $('#LastName').val(),
                "DOB": $('#DOB').val(),
                "Gender": $('#Gender').val(),
                "Nationality": $('#Nationality').val(),
                "Language": $('#Language').val(),
                "Address": $('#Address').val()
            };

            $.ajax({
                type: "POST",
                url: "api/Employee",
                data: JSON.stringify(employeeData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data, status, jqXHR) {
                    alert("Successsfully added…. " + employeeData.EmployeeID);
                    GelAllEmployees();
                    ClearForm();
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        }


Update Employee

function UpdateEmployee() {
            var employeeData = {
                "EmployeeID": $('#EmployeeID').val(),
                "FirstName": $('#FirstName').val(),
                "LastName": $('#LastName').val(),
                "DOB": $('#DOB').val(),
                "Gender": $('#Gender').val(),
                "Nationality": $('#Nationality').val(),
                "Language": $('#Language').val(),
                "Address": $('#Address').val()
            };
            $.ajax({
                type: "PUT",
                url: "api/Employee/" + employeeData.EmployeeID,
                data: JSON.stringify(employeeData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data, status, jqXHR) {
                    alert("Successfully updated…" + employeeData.EmployeeID);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        }


Delete Employee

function DeleteEmployee(EmployeeID) {
            var txt;
            var r = confirm("Are you sure you want to delete this recored?");
            if (r == true) {
                $.ajax({
                    type: "DELETE",
                    url: "api/Employee/" + EmployeeID,
                    contentType: "json",
                    dataType: "json",
                    success: function (data) {
                        alert("Successsfully deleted…. " + EmployeeID);
                    },
                    error: function (xhr) {
                        alert(xhr.responseText);
                    }
                });
                GelAllEmployees();
            } else {
            }
        }


Clear form

  function ClearForm() {
            $('#EmployeeID').val("");
            $('#FirstName').val("");
            $('#LastName').val("");
            $('#DOB').val("");
            $('#Gender').val("");
            $('#Nationality').val("");
            $('#Language').val("");
            $('#Address').val("");
            $('#AddUpdate').val("Create");
        }


Create or Update decider function

  function ADDUpdate() {
            var btn = $('#AddUpdate').val();
            if (btn == "Create") {
                AddNewEmployee();
            }
            if (btn == "Update") {
                UpdateEmployee();
            }
        }


Add this script to get reference of JQuery.

 <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>