WebAPI笔记:WebAPI+AJAX实现CRUD实例

详细代码链接

创建控制器api

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiAjaxCRUD.Models;

namespace WebApiAjaxCRUD.Controllers
{
    public class EmployeeController : ApiController
    {
        Models.WebApiAjaxCRUDEntities db = new Models.WebApiAjaxCRUDEntities();

        // GET api/EmployeesAPI
        [Route("api/EmployeesAPI")]
        public IEnumerable<Employee> GetEmployees()
        {
            return db.Employees.AsEnumerable();
        }

        // GET api/EmployeesAPI/5
        [Route("api/EmployeesAPI/{id}")]
        public Employee GetEmployee(int id)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return employee;
        }

        // PUT api/EmployeesAPI/5
        [Route("api/EmployeesAPI")]
        public IHttpActionResult PutEmployee(Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return Ok();
            }
            else
            {
                return NotFound();
            }
        }

        // POST api/EmployeesAPI
        [Route("api/EmployeesAPI")]
        public IHttpActionResult PostEmployee(Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return Ok();
            }
            else
            {
                return NotFound();
            }
        }

        // DELETE api/EmployeesAPI/5
        [Route("api/EmployeesAPI/{id}")]
        public IHttpActionResult DeleteEmployee(int id)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return NotFound();
            }

            db.Employees.Remove(employee);
            db.SaveChanges();

            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

创建ajax JavaScript ui文件

$(document).ready(function () {
    GetAllEmployees();
});

function GetAllEmployees() {
    $.ajax({
        url: 'api/EmployeesAPI',
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var html = '';
            $.each(result, function (key, item) {
                html += '<tr>';
                html += '<td>' + item.EmployeeID + '</td>';
                html += '<td>' + item.Name + '</td>';
                html += '<td>' + item.Age + '</td>';
                html += '<td>' + item.State + '</td>';
                html += '<td>' + item.Country + '</td>';
                html += '<td><a href="#" οnclick="return GetEmployeeByID(' + item.EmployeeID + ')">Edit</a> | <a href="#" οnclick="DeleteEmployee(' + item.EmployeeID + ')">Delete</a></td>';
                html += '</tr>';
            });
            $('.tbody').html(html);
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
}

function GetEmployeeByID(employeeId) {
    $('#Name').css('border-color', 'lightgrey');
    $('#Age').css('border-color', 'lightgrey');
    $('#State').css('border-color', 'lightgrey');
    $('#Country').css('border-color', 'lightgrey');

    $.ajax({
        url: 'api/EmployeesAPI/' + employeeId,
        type: 'GET',
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (result) {
            $('#EmployeeID').val(result.EmployeeID);
            $('#Name').val(result.Name);
            $('#Age').val(result.Age);
            $('#State').val(result.State);
            $('#Country').val(result.Country);

            $('#myModal').modal('show');
            $('#btnUpdate').show();
            $('#btnAdd').hide();
        },
        error: function (errormessage) {            
            alert(errormessage.responseText);
        }
    });
}

function AddEmployee() {
    var res = Validate();
    if (res == false) {
        return false;
    }

    var employeeObject = {
        Name: $('#Name').val(),
        Age: $('#Age').val(),
        State: $('#State').val(),
        Country: $('#Country').val()
    };
   
    $.ajax({
        url: 'api/EmployeesAPI',
        type: 'POST',
        data: JSON.stringify(employeeObject),
        contentType: "application/json;charset=utf-8",
        success: function (result) {           
            GetAllEmployees();
            $('#myModal').modal('hide');            
            $('.modal-backdrop').remove();
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
}

function UpdateEmployee() {
    var res = Validate();
    if (res == false) {
        return false;
    }

    var employeeObject = {
        EmployeeID: $('#EmployeeID').val(),
        Name: $('#Name').val(),
        Age: $('#Age').val(),              
        State: $('#State').val(),
        Country: $('#Country').val()
    };

    $.ajax({
        url: 'api/EmployeesAPI/',
        type: 'PUT',
        data: JSON.stringify(employeeObject),
        contentType: "application/json;charset=utf-8",
        success: function (result) {
            GetAllEmployees();
            $('#myModal').modal('hide');
            $('#EmployeeID').val("");
            $('#Name').val("");
            $('#Age').val("");
            $('#State').val("");
            $('#Country').val("");
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
}

function DeleteEmployee(employeeId) {
    bootbox.confirm("Are you sure you want to delete?", function(result){  
        if (result) {
            $.ajax({
                url: 'api/EmployeesAPI/' + employeeId,
                type: 'DELETE',
                data: 'json',
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    GetAllEmployees();
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
        }
    })
}

function Validate() {
    var isValid = true;
    if ($('#Name').val().trim() == "") {
        $('#Name').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#Name').css('border-color', 'lightgrey');
    }
    if ($('#Age').val().trim() == "") {
        $('#Age').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#Age').css('border-color', 'lightgrey');
    }
    if ($('#State').val().trim() == "") {
        $('#State').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#State').css('border-color', 'lightgrey');
    }
    if ($('#Country').val().trim() == "") {
        $('#Country').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#Country').css('border-color', 'lightgrey');
    }
    return isValid;
}

function clearTextBox() {
    $('#EmployeeID').val("");
    $('#Name').val("");
    $('#Age').val("");
    $('#State').val("");
    $('#Country').val("");
    $('#btnUpdate').hide();
    $('#btnAdd').show();
    $('#Name').css('border-color', 'lightgrey');
    $('#Age').css('border-color', 'lightgrey');
    $('#State').css('border-color', 'lightgrey');
    $('#Country').css('border-color', 'lightgrey');
}


在layout文件中引入ajax JavaScript ui文件和其他相关js文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/bootbox/bootbox.min.js"></script>
    <script src="~/Scripts/bootbox/bootbox.locales.min.js"></script>
    <script src="~/Scripts/CustomScripts/employee.js"></script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("A Sample CRUD Application", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
                    <li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_39827640/article/details/107550922