iT邦幫忙

2021 iThome 鐵人賽

DAY 2
2
自我挑戰組

.NET Core WebApi網頁應用開發系列 第 5

.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>

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

https://ithelp.ithome.com.tw/upload/images/20210905/20107452iF2ng9rJB9.png

本文已同步發表至個人部落格
https://coolmandiary.blogspot.com/2021/09/net-core-web-api05httpdelete.html


上一篇
.Net Core Web Api_筆記04_HTTP資源操作模式Put
下一篇
.Net Core Web Api_筆記06_HTTP資源操作模式Head
系列文
.NET Core WebApi網頁應用開發25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言