Jquery调用Web API实例

本文介绍了一个学生信息管理系统Web API的设计与实现。该系统提供了增删改查等基本操作,并通过jQuery实现了前端交互。涵盖RESTful风格的接口设计及数据操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下

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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值