.Net Core Web Api_筆記05_HTTP資源操作模式Delete

 一般而言會接收Id (可能是個Pk 唯一值)來進行刪除操作

這裡一樣是新增刪除action在上幾篇的TeacherController.cs當中

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyApiTest1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApiTest1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TeacherController : ControllerBase
    {
        [HttpPost("Add")]
        public string AddPerson(Person person)
        {
            int id = person.Id;
            string name = person.Name;
            int age = person.Age;
            string sex = person.Sex;
            return "完成添加";
        }

        [HttpPut("Update")]
        public string UpdatePerson(Person person)
        {
            int id = person.Id;
            string name = person.Name;
            int age = person.Age;
            string sex = person.Sex;
            return "完成更新";
        }


        [HttpDelete("Delete")]
        public string DeletePerson(string id)
        {
            string msg = "";
            if (!string.IsNullOrEmpty(id))
            {
                var strId = id;
                //刪除作業.....

                //刪除作業.....
                msg = "完成刪除";
            }
            return msg;
        }

    }
}



前端部分
新增一個簡單的html檔 DeleteTeacher.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Delete Teacher Info</title>
    <script src="jquery/jquery.min.js"></script>
</head>
<body>
    <div>
        <input type="button" id="btnDelete" value="刪除" />
        <span id="msg"></span>
    </div>

    <script type="text/javascript">
        $("#btnDelete").click(function () {
            $.ajax({
                //請求模式
                type: "delete",
                //請求的URL
                url: "api/Teacher/Delete?id=200",
                //預期server responde的資料型態
                dataType: "text",
                success: function (result) {
                    $("#msg").text(result);
                }
            });
        });
    </script>
</body>
</html>

運行效果去模擬發送刪除請求的過程跟文字回應






留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題