1. 程式人生 > >Jquery呼叫Web API例項

Jquery呼叫Web API例項

程式碼如下

Web API程式碼

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

namespace StudentApplication.Controllers
{
    public class StudentValueController : ApiController
    {
        /// <summary>
        /// 獲取所有的學生資訊
        /// GET /api/StudentValue/GetAllStudents
        /// </summary>
        /// <returns>所有的學生資訊</returns>
        [HttpGet]
        public IEnumerable<StudentInfo> GetAllStudents()
        {
            using (DataClassesDataContext dcdc = new DataClassesDataContext())
            {
                return dcdc.StudentInfos.ToList();
            }
        }
        /// <summary>
        /// 根據搜尋條件獲取學生資訊
        /// POST /api/StudentValue/GetStudents
        /// </summary>
        /// <param name="item">搜尋條件</param>
        /// <returns>滿足條件的學生資訊</returns>
        [HttpPost]
        public IEnumerable<StudentInfo> GetStudents(StudentInfo query)
        {
            using (DataClassesDataContext dcdc = new DataClassesDataContext())
            {
                List<StudentInfo> items = dcdc.StudentInfos.ToList();
                if (query.stuName != null)
                {
                    items=items.Where(u => u.stuName.Contains(query.stuName)).ToList();
                }
                if (query.stuAddress != null)
                {
                    items = items.Where(u => u.stuAddress.Contains(query.stuAddress)).ToList();
                }
                return items;
            }
        }
        /// <summary>
        /// 根據學生編號獲取學生資訊
        /// GET /api/StudentValue/GetStudentById/{id}
        /// </summary>
        /// <param name="id">編號</param>
        /// <returns>學生資訊</returns>
        [HttpGet]
        public StudentInfo GetStudentById(int id)
        {
            using (DataClassesDataContext dcdc = new DataClassesDataContext())
            {
                return dcdc.StudentInfos.FirstOrDefault(u => u.stuId.Equals(id));
            }
        }
        /// <summary>
        /// 新增學生資訊
        /// POST /api/StudentValue/AddStudent
        /// {stuName:'jack', stuAddress:'jiangsu'}
        /// </summary>
        /// <param name="item">學生資訊</param>
        /// <returns>新增成功返回true, 否則返回false</returns>
        [HttpPost]
        public bool AddStudent(StudentInfo item)
        {
            try
            {
                using (DataClassesDataContext dcdc = new DataClassesDataContext())
                {
                    dcdc.StudentInfos.InsertOnSubmit(item);
                    dcdc.SubmitChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 修改學生資訊
        /// PUT /api/StudentValue/UpdateStudent/{id}
        /// {stuName:'jack', stuAddress:'jiangsu'}
        /// </summary>
        /// <param name="id">編號</param>
        /// <param name="item">新的學生資訊</param>
        /// <returns>更新成功返回true, 否則返回false</returns>
        [HttpPut]
        public bool UpdateStudent(int id, StudentInfo item)
        {
            try
            {
                using (DataClassesDataContext dcdc = new DataClassesDataContext())
                {
                    StudentInfo info = dcdc.StudentInfos.FirstOrDefault(u => u.stuId == id);
                    info.stuName = item.stuName;
                    info.stuAddress = item.stuAddress;
                    dcdc.SubmitChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 刪除學生資訊
        /// DELETE /api/StudentValue/DeleteStudent/{id}
        /// </summary>
        /// <param name="id">編號</param>
        /// <returns>刪除成功返回true, 否則返回false</returns>
        public bool DeleteStudent(int id)
        {
            try
            {
                using (DataClassesDataContext dcdc = new DataClassesDataContext())
                {
                    StudentInfo item = dcdc.StudentInfos.FirstOrDefault(u => u.stuId.Equals(id));
                    dcdc.StudentInfos.DeleteOnSubmit(item);
                    dcdc.SubmitChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
Jquery程式碼
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Student Index</title>
    <style>
        .odd_class
        {
            background-color: #ebebeb;
        }

        .click_class
        {
            background-color: #bdd2f1;
        }
    </style>
    <script type="text/javascript" src="../../Scripts/jquery-1.7.1.min.js"></script>
    <script type="text/javascript">
        var studentId = 0;//儲存學生編號
        $(function () {
            $('#btnSearch').click(function () {
                displayStudents();
            }).triggerHandler('click');
            $('#btnAdd').click(function () {//單擊Add按鈕將<div id="operation">中的控制元件disabled=false
                disableOperation(false);
            });
            $('#btnClear').click(function () {//單擊Clear按鈕清空文字
                clearTextBox();
            });
            $('#btnSubmit').click(function () {//新增,更新學生資訊
                var student = {};
                var name = $('#txtName').val();
                if (name == '') {
                    alert('Please input name!');
                    return;
                }
                var address = $('#txtAddress').val();
                if (address == '') {
                    alert('Please input address');
                    return;
                }
                student.stuName = name;
                student.stuAddress = address;
                var stuJson = JSON.stringify(student);//將student物件轉換成json
                if (studentId == 0) {//新增
                    $.ajax({
                        type: 'POST',
                        url: '/api/StudentValue/AddStudent',
                        data: stuJson,
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        success: function (data) {
                            if (data) {
                                clearTextBox();
                                displayStudents();
                            } else {
                                alert('Add student failed.');
                            }
                        },
                        error: function (msg) {
                            alert(msg.responseText);
                        }
                    });
                } else {//更新
                    $.ajax({
                        type: 'PUT',
                        url: '/api/StudentValue/UpdateStudent/' + studentId,
                        data: stuJson,
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        success: function (data) {
                            if (data) {
                                studentId = 0;
                                clearTextBox();
                                displayStudents();
                            } else {
                                alert('update student failed.');
                            }
                        },
                        error: function (msg) {
                            alert(msg.responseText);
                        }
                    });
                }
            });
            $('#btnDelete').click(function () {//刪除學生資訊
                if (studentId == 0) {
                    alert('Please select student which you want to delete.');
                    return;
                }
                if (confirm('Do you want to delete the selected student?')) {
                    $.ajax({
                        type: 'DELETE',
                        url: '/api/StudentValue/DeleteStudent/'+studentId,
                        success: function (data) {
                            if (data) {
                                studentId = 0;
                                clearTextBox();
                                displayStudents();
                            } else {
                                alert('delete student failed.');
                            }
                        },
                        error: function (msg) {
                            alert(msg.responseText);
                        }
                    });
                }
            });
        });
        //如果flag=true,將<div id="operation">中的控制元件不可編輯;
        //如果flag=false,將<div id="operation">中的控制元件可編輯;
        function disableOperation(flag) {
            if (flag) {
                $('#txtName').attr('disabled', 'disabled');
                $('#txtAddress').attr('disabled', 'disabled');
                $('#btnSubmit').attr('disabled', 'disabled');
                $('#btnClear').attr('disabled', 'disabled');
                $('#btnDelete').attr('disabled', 'disabled');
            } else {
                $('#txtName').removeAttr('disabled');
                $('#txtAddress').removeAttr('disabled');
                $('#btnSubmit').removeAttr('disabled');
                $('#btnClear').removeAttr('disabled');
                $('#btnDelete').removeAttr('disabled');
            }
        }
        //清空操作編辦文字框
        function clearTextBox() {
            $('#txtName').val('');
            $('#txtAddress').val('');
        }
        //根據搜尋條件顯示學生資訊
        function displayStudents() {
            var student = {};
            var name = $('#txtSearchName').val();
            if (name != '') {
                student.stuName = name;
            }
            var address = $('#txtSearchAddress').val();
            if (address != '') {
                student.stuAddress = address;
            }
            var stuJson = JSON.stringify(student);
            $.ajax({
                type: 'POST',
                url: '/api/StudentValue/GetStudents',
                data: stuJson,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data) {
                    disableOperation(true);
                    $('#students').empty();
                    if (data.length > 0) {
                        var html = '';
                        html += '<table style=" width:400px; text-align:left;" border="0" cellspacing="0" cellpadding="0">';
                        html += '<tr><th style=" width:40%;">name</th><th style=" width:60%; text-align:left;">address</th></tr>';
                        $.each(data, function (key, val) {
                            html += '<tr id="' + val.stuId + '"><td>' + val.stuName + '</td><td>' + val.stuAddress + '</td></tr>';
                        });
                        html += '</table>';
                        $('#students').append(html);
                        $('#students>table>tbody>tr:odd').addClass('odd_class');//偶數行新增背景顏色
                        $('#students>table>tbody>tr').click(function () {//單擊行新增高亮
                            $(this).addClass('click_class')
                                    .siblings().removeClass('click_class');
                            disableOperation(false);
                            studentId = $(this).attr('id');
                            displayStudentById(studentId);
                        });
                    }
                },
                error: function (msg) {
                    alert(msg.responseText);
                }
            });
        }
        //根據編號顯示學生資訊
        function displayStudentById(id) {
            $.getJSON('/api/StudentValue/GetStudentById/' + id, function (data) {
                if (data != null) {
                    $('#txtName').val(data.stuName);
                    $('#txtAddress').val(data.stuAddress);
                }
            }).fail(function (msg) {
                alert(msg.responseText);
            });
        }
    </script>
</head>
<body>
    <fieldset>
        <legend>search criteria</legend>
        <div id="search">
            <table>
                <tr>
                    <td>name</td>
                    <td>
                        <input id="txtSearchName" type="text" /></td>
                    <td>address</td>
                    <td>
                        <input id="txtSearchAddress" type="text" /></td>
                    <td>
                        <input id="btnSearch" type="button" value="Search"></td>
                    <td>
                        <input id="btnAdd" type="button" value="Add"></td>
                </tr>
            </table>
        </div>
    </fieldset>
    <fieldset>
        <legend>students</legend>
        <div id="students">
        </div>
    </fieldset>
    <fieldset>
        <legend>operation</legend>
        <div id="operation">
            <table>
                <tr>
                    <td>name</td>
                    <td>
                        <input id="txtName" type="text" /></td>
                    <td></td>
                </tr>
                <tr>
                    <td>address</td>
                    <td>
                        <input id="txtAddress" type="text" /></td>
                </tr>
                <tr>
                    <td>
                        <input id="btnSubmit" type="button" value="submit" /></td>
                    <td>
                        <input id="btnClear" type="button" value="clear" />
                        <input id="btnDelete" type="button" value="delete" /></td>
                </tr>
            </table>
        </div>
    </fieldset>
</body>
</html>