DNK Gif

Dot Net Knowledge

Labels

Sunday, 17 April 2016

Consume REST Api or Web Api using Jquery for all CRUD(Create, Read, Update, Delete) Operations

Consume ASP.NET Web Api using Jquery for all CRUD(Create, Read, Update, Delete) Operations


Here is the HTML Codes:-

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Employee</title>    
    <script src="Scripts/bootstrap.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
    <script src="Scripts/modernizr-2.6.2.js"></script>
    <script src="Scripts/jquery-1.10.2.intellisense.js"></script>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script src="Scripts/respond.js"></script>    
    <script src="Scripts/respond.min.js"></script>
    <style type="text/css">
        .CSSTableGenerator {
            margin: 0px;
            padding: 0px;
            width: 100%;
            box-shadow: 10px 10px 5px #888888;
            border: 1px solid #000000;
            -moz-border-radius-bottomleft: 0px;
            -webkit-border-bottom-left-radius: 0px;
            border-bottom-left-radius: 0px;
            -moz-border-radius-bottomright: 0px;
            -webkit-border-bottom-right-radius: 0px;
            border-bottom-right-radius: 0px;
            -moz-border-radius-topright: 0px;
            -webkit-border-top-right-radius: 0px;
            border-top-right-radius: 0px;
            -moz-border-radius-topleft: 0px;
            -webkit-border-top-left-radius: 0px;
            border-top-left-radius: 0px;
        }

            .CSSTableGenerator table {
                border-collapse: collapse;
                border-spacing: 0;
                width: 100%;
                height: 100%;
                margin: 0px;
                padding: 0px;
            }

            .CSSTableGenerator tr:last-child td:last-child {
                -moz-border-radius-bottomright: 0px;
                -webkit-border-bottom-right-radius: 0px;
                border-bottom-right-radius: 0px;
            }

            .CSSTableGenerator table tr:first-child td:first-child {
                -moz-border-radius-topleft: 0px;
                -webkit-border-top-left-radius: 0px;
                border-top-left-radius: 0px;
            }

            .CSSTableGenerator table tr:first-child td:last-child {
                -moz-border-radius-topright: 0px;
                -webkit-border-top-right-radius: 0px;
                border-top-right-radius: 0px;
            }

            .CSSTableGenerator tr:last-child td:first-child {
                -moz-border-radius-bottomleft: 0px;
                -webkit-border-bottom-left-radius: 0px;
                border-bottom-left-radius: 0px;
            }

            .CSSTableGenerator tr:hover td {
            }

            .CSSTableGenerator tr:nth-child(odd) {
                background-color: #ffaa56;
            }

            .CSSTableGenerator tr:nth-child(even) {
                background-color: #ffffff;
            }

            .CSSTableGenerator td {
                vertical-align: middle;
                border: 1px solid #000000;
                border-width: 0px 1px 1px 0px;
                text-align: left;
                padding: 7px;
                font-size: 10px;
                font-family: Arial;
                font-weight: normal;
                color: #000000;
            }

            .CSSTableGenerator tr:last-child td {
                border-width: 0px 1px 0px 0px;
            }

            .CSSTableGenerator tr td:last-child {
                border-width: 0px 0px 1px 0px;
            }

            .CSSTableGenerator tr:last-child td:last-child {
                border-width: 0px 0px 0px 0px;
            }

            .CSSTableGenerator tr:first-child td {
                background: -o-linear-gradient(bottom, #ff7f00 5%, #bf5f00 100%);
                background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ff7f00), color-stop(1, #bf5f00) );
                background: -moz-linear-gradient( center top, #ff7f00 5%, #bf5f00 100% );
                filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ff7f00", endColorstr="#bf5f00");
                background: -o-linear-gradient(top,#ff7f00,bf5f00);
                background-color: #ff7f00;
                border: 0px solid #000000;
                text-align: center;
                border-width: 0px 0px 1px 1px;
                font-size: 14px;
                font-family: Arial;
                font-weight: bold;
                color: #ffffff;
            }

            .CSSTableGenerator tr:first-child:hover td {
                background: -o-linear-gradient(bottom, #ff7f00 5%, #bf5f00 100%);
                background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ff7f00), color-stop(1, #bf5f00) );
                background: -moz-linear-gradient( center top, #ff7f00 5%, #bf5f00 100% );
                filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ff7f00", endColorstr="#bf5f00");
                background: -o-linear-gradient(top,#ff7f00,bf5f00);
                background-color: #ff7f00;
            }

            .CSSTableGenerator tr:first-child td:first-child {
                border-width: 0px 0px 1px 0px;
            }

            .CSSTableGenerator tr:first-child td:last-child {
                border-width: 0px 0px 1px 1px;
            }
    </style>
</head>
<body>
    <div class="container">
        <div class="row" id="AllEmployees">
            <div class="col-md-12">
                <h3> Get All Employees</h3>
            </div>
            <div class="col-md-12">
                <input type="button" id="btnGetAllEmployees" value="Go" />
            </div>
            <div class="col-md-12" id="tblAllEmployee">                
            </div>
        </div>

        <div class="row" id="SingleEmployee">
            <div class="col-md-12">
                <h3> Get Employee by Id</h3>
            </div>
            <div class="col-md-6">
                <input type="text" id="txtSearchEmpId" />
            </div>
            <div class="col-md-6">
                <input type="button" id="btnGetEmployeeById" value="Go" />
            </div>
            <div class="col-md-12" id="singleEmp">
                <div class="col-md-12">
                    <span>Employee Id: </span><span id="spnEmpId"></span>
                </div>
                <div class="col-md-12">
                    <span>Employee Name: </span><span id="spnEmpName"></span>
                </div>
                <div class="col-md-12">
                    <span>Contact Number: </span><span id="spnContact"></span>
                </div>


                </div>
        </div>

        <div class="row" id="CreateEmployee">
            <div class="col-md-12">
                <h3> Add Employee</h3>
            </div>            
            
            <div class="col-md-12" id="singleEmp">
                <div class="col-md-12">
                    <span>Employee Id: </span><span id="spnEmpId"></span>
                </div>
                <div class="col-md-12">
                    <span>Employee Name: </span><span id="spnEmpName"><input type="text" id="txtEmpName" /></span>
                </div>
                <div class="col-md-12">
                    <span>Contact Number: </span><span id="spnContact"><input type="text" id="txtEmpContact" /></span>
                </div>
                <div class="col-md-12">
                    <input type="button" id="btnAddEmployee" value="Create" />
                </div>

            </div>
        </div>

        <div class="row" id="UpdateEmployee">
            <div class="col-md-12">
                <h3> Update Employee</h3>
            </div>

            <div class="col-md-12" id="singleEmp">
                <div class="col-md-12">
                    <span>Employee Id: </span><span id="spnEmpId"><input type="text" id="txtEmpId" /></span>
                </div>
                <div class="col-md-12">
                    <span>Employee Name: </span><span id="spnEmpName"><input type="text" id="txtEmpName" /></span>
                </div>
                <div class="col-md-12">
                    <span>Contact Number: </span><span id="spnContact"><input type="text" id="txtEmpContact" /></span>
                </div>
                <div class="col-md-12">
                    <input type="button" id="btnUpdateEmployee" value="Update" />
                </div>

            </div>
        </div>

        <div id="DeleteEmployee" class="row">
            <div class="col-md-12">
                <h3> Delete Employee by Id</h3>
            </div>
            <div class="col-md-6">
                <input type="text" id="txtSearchEmpId" />
            </div>
            <div class="col-md-6">
                <input type="button" id="btnDeleteEmployeeById" value="Delete" />
            </div>
            <div class="col-md-12" id="msg">


            </div>
        </div>
    </div>
    <script src="Scripts/Employee.js"></script>
</body>
</html>

Here is the .js file Codes:-

$(document).ready(function () {
    var view = GetParameterValues('View');
    //var id = GetParameterValues('ID');
    //alert("Hello " + name + " your ID is " + id);
    switch(view.toLowerCase())
    {
        case 'getall':
            $('#SingleEmployee').remove();
            //$('#SingleEmployee').find('*').prop('disabled', true);
            $('#CreateEmployee').remove();
           // $('#CreateEmployee').find('*').prop('disabled', true);
            $('#UpdateEmployee').remove();
            //$('#UpdateEmployee').find("*").prop('disabled',true);
            $('#DeleteEmployee').remove();
            //$('#DeleteEmployee').find("*").prop('disabled',true);
            $('#AllEmployees').show();
            break;
        case 'get':
            $('#SingleEmployee').show();
            $('#CreateEmployee').remove();
            $('#UpdateEmployee').remove();
            $('#DeleteEmployee').remove();
            $('#AllEmployees').remove();
            break;
        case 'create':
            $('#SingleEmployee').remove();
            $('#CreateEmployee').show();
            $('#UpdateEmployee').remove();
            $('#DeleteEmployee').remove();
            $('#AllEmployees').remove();
            break;
        case 'update':
            $('#SingleEmployee').remove();
            $('#CreateEmployee').remove();
            $('#UpdateEmployee').show();
            $('#DeleteEmployee').remove();
            $('#AllEmployees').remove();
            break;
        case 'delete':
            $('#SingleEmployee').remove();
            $('#CreateEmployee').remove();
            $('#UpdateEmployee').remove();
            $('#DeleteEmployee').show();
            $('#AllEmployees').remove();
            break;
        default:        
            $('#SingleEmployee').show();
            $('#CreateEmployee').show();
            $('#UpdateEmployee').show();
            $('#DeleteEmployee').show();
            $('#AllEmployees').show();
            break;
    }
    
    $('#btnGetEmployeeById').click(function () {       
        var request = $.ajax({
            url: 'http://localhost:55718/api/Employee/GetEmployeeDetails',
            type: 'GET',
            data: { id: $('#txtSearchEmpId').val() },

        });

        request.success(function (result) {
            console.log(JSON.stringify(result));
            $('#spnEmpId').html(result.EmployeeId);
            $('#spnContact').html(result.ContactNumber);
            $('#spnEmpName').html(result.Name);
        });

        request.error(function (jqXHR, textStatus) {
            alert('An error occurred ' + JSON.stringify(jqXHR) + textStatus);
        });

        request.fail(function (jqXHR, textStatus) {
            alert('Request failed ' + JSON.stringify(jqXHR) + textStatus);
        });
    });

    $('#btnGetAllEmployees').click(function () {
        
        $.ajax({
            url: 'http://localhost:55718/api/Employee/GetEmployees',
            type:'GET',
            data:{},
            success: function(result)
            {
                console.log(JSON.stringify(result));
                CreateTable(result);
            },
            error:function(jqXHR,textStatus){
                alert('An error occurred ' + JSON.stringify(jqXHR) + textStatus);
            }

        });
    });

    $('#btnAddEmployee').click(function () {
        var isValidationPassed = true;
        var name = $('#txtEmpName').val();
        var contact = $('#txtEmpContact').val();
        if ((name == '' || name == null || name == 'undefined') && (contact == '' || contact == null || contact == 'undefined')) {
            isValidationPassed = false;
            alert('Please enter Employee Name & Contact Number.');
        }
        else {

            var regExpr = new RegExp('/^[a-zA-Z]+$/', 'g');
            //if (regExpr.test(name)) {
            //    isValidationPassed = true;
            //}
            //else {
            //    isValidationPassed = false;
            //    alert('Please enter only alphabets in the Employee Name field.');
            //}
            //regExpr = new RegExp('/^\d+$/','g');
            //if (contact.match(regExpr)) {
            //    isValidationPassed = true;
            //}
            //else {
            //    isValidationPassed = false;
            //    alert('Please enter only number in the Contact Number field.');
            //}
            isValidationPassed = true;

        }
        var model = {
            'Name': name,
            'ContactNumber': contact,
            'EmployeeId': ''
        };
        if (isValidationPassed) {
            $.ajax({

                url: 'http://localhost:55718/api/Employee/AddEmployee',
                type: 'POST',
                data: model,
                success: function (result) {
                    alert(result);
                },
                error: function (jqXHR, textStatus) {
                    alert('An error occurred ' + JSON.stringify(jqXHR) + textStatus);
                }
            });
        }
    });

    $('#btnUpdateEmployee').click(function () {
        var model = {
            'Name': $('#txtEmpName').val(),
            'ContactNumber': $('#txtEmpContact').val(),
            'EmployeeId': $('#txtEmpId').val()
        };
        $.ajax({
            url: 'http://localhost:55718/api/Employee/UpdateEmployeeDetails',
            type: 'POST',
            data: model,
            success: function (result) {
                alert(result);
            },
            error: function (jqXHR, textStatus) {
                alert('An error occurred ' + JSON.stringify(jqXHR) + textStatus);
            }
        });
    });

    $('#btnDeleteEmployeeById').click(function () {        
        var searchEmpId = $('#txtSearchEmpId').val();        
        $.ajax({
            type: 'POST',
            url: 'http://localhost:55718/api/Employee/DeleteEmployee?' + jQuery.param({ id: searchEmpId }),
            contentType:'application/json; charset=utf-8',
            data: jQuery.param({ id: searchEmpId }),
            dataType:'json',
            success: function (result) {
                alert(result);
                //location.href = 'Employee.html?view=getall';
            },
            error: function (jqXHR, textStatus) {
                alert('An error occurred ' + JSON.stringify(jqXHR) + textStatus);
            }
        });
    });
});

function GetParameterValues(param) {
    var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < url.length; i++) {
        var urlparam = url[i].split('=');
        if (urlparam[0].toLowerCase() == param.toLowerCase()) {
            return urlparam[1];
        }
    }
}

function CreateTable(data) {
    var parentDivTable = document.getElementById('tblAllEmployee');
    var table = document.createElement('table');
    table.setAttribute('border', '1');
    table.setAttribute('class', 'CSSTableGenerator');
    var thead = document.createElement('thead');
    var tbody = document.createElement('tbody');
    var tr = document.createElement('tr');
    var td = document.createElement('td');    
    var header = ['Employee Id', 'Employee Name', 'Contact Number'];    
    var i = 0;
    for (i = 0; i < header.length; i++)
    {        
        td = document.createElement('th');
        
        td.innerHTML = header[i];
        tr.appendChild(td);
    }
    thead.appendChild(tr);   
    
    for (i = 0; i < data.length; i++)
    {
        tdEmpId = document.createElement('td');
        tdEmpId.innerHTML = data[i].EmployeeId;
        tdEmpName = document.createElement('td');
        tdEmpName.innerHTML = data[i].Name;
        tdContactNumber = document.createElement('td');
        tdContactNumber.innerHTML = data[i].ContactNumber;
        tr = document.createElement('tr');
        tr.appendChild(tdEmpId);
        tr.appendChild(tdEmpName);
        tr.appendChild(tdContactNumber);
        tbody.appendChild(tr);
    }    
    table.appendChild(thead);
    table.appendChild(tbody);
    while (parentDivTable.hasChildNodes())
    {
        parentDivTable.removeChild(parentDivTable.firstChild);
    }
    parentDivTable.appendChild(table);
}



No comments:

Post a Comment