.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>
運行效果去模擬發送刪除請求的過程跟文字回應
留言
張貼留言