iT邦幫忙

2021 iThome 鐵人賽

DAY 2
2
自我挑戰組

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

.Net Core Web Api_筆記04_HTTP資源操作模式Put

基本上跟POST是有點類似的作法
通常用於資料更新(所以資料必須是已存在於目前db的)

新增額外的action method for更新

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 "完成更新";
        }

    }
}

然後在額外新增一html檔案用於更新教師資訊的測試頁面
UpdateTeacher.html

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

    <script type="text/javascript">
        $("#btnUpdate").click(function () {
            $.ajax({
                //請求模式
                type: "put",
                //請求的URL
                url: "api/Teacher/Update",
                //預期server responde的資料型態
                dataType: "text",
                //請求送出發送的資料(body內文json字串)
                data: JSON.stringify({ id: 1, name: 'Andy', age: 22, sex: 'man' }),
                //內文型態
                contentType: "application/json",
                success: function (result) {
                    $("#msg").text(result);
                }
            });
        });
    </script>
</body>
</html>

基本上跟POST使用沒有太大落差只在於type調整
運行效果
https://ithelp.ithome.com.tw/upload/images/20210905/20107452LeaOibEyj8.png

以上就是本次介紹的HttpPut操作測試模擬

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


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

尚未有邦友留言

立即登入留言