iT邦幫忙

2021 iThome 鐵人賽

DAY 2
0
自我挑戰組

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

.Net Core Web Api_筆記16_api結合ADO.NET資料庫操作part4_資料編輯提交更新

編輯則是會By特定編號撈取指定資料去做編輯
所以需要先把資料回填到表單
修改Show.html
這裡改一下標題為操作(包含編輯,刪除兩種操作類型)

https://ithelp.ithome.com.tw/upload/images/20210930/201074522pirRfDKYl.png

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Show NewsType</title>
    <link href="../css/bootstrap.min.css" rel="stylesheet" />
    <script src="../js/jquery/jquery.min.js"></script>
</head>
<body style="margin:20px;">
    <table id="tbNewsType" class="table table-bordered">
        <thead>
            <tr>
                <td>文章ID</td>
                <td>分類</td>
                <td>是否啟用</td>
                <td>操作</td>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    <script type="text/javascript">
        $(function () {
            var tbody = $('#tbNewsType tbody')
            $.ajax({
                type: 'get',
                url: '/api/NewsType/Show',
                dataType: 'json',
                success: function (result) {
                    $.each(result, function (n, value) {
                        var IsEnabled;
                        value.isEnabled ? IsEnabled = '啟用' : IsEnabled = '關閉';
                        var tr_val = "";
                        tr_val += "<tr><td>" + value.newsTypeId
                            + "</td><td>" + value.newsTypeName
                            + "</td><td>" + IsEnabled
                            + "</td><td><a href='Edit.html?id=" + value.newsTypeId + "'>編輯</a> " 
                            + "<a href='javascript:Del(" + value.newsTypeId + ")'>刪除</a>"                            
                            + "</td></tr>";
                        tbody += tr_val;
                    });
                    $('#tbNewsType').append(tbody);
                }
            });
        });

        function Del(id) {
            $.ajax({
                type: "delete",
                url: "/api/newstype/delete?id=" + id,
                dataType: "json",
                success: function (result) {
                    if (result != "0") {
                        location.href = "Show.html";
                    }
                }
            });
        }
    </script>
</body>
</html>

擴充Action Method
GetSpecificNewsTypeById
幫我們把資料查詢用來後續回填至畫面上

[HttpGet("GetById")]
public ActionResult<NewsType> GetSpecificNewsTypeById(int? id)
{
    if (id == null)
        return NotFound();

    string strSQL = "select * from NewsType where NewsTypeId=@Id";
    Hashtable htParams = new Hashtable();
    htParams.Add("@Id", id);
    SqlDataReader dataReader = MSSQLHelper.GetSqlDataReader(strSQL,htParams);
    NewsType newsType = new NewsType();
    while (dataReader.Read())
    {
        newsType.NewsTypeId = dataReader.GetInt32(0);
        newsType.NewsTypeName = dataReader.GetString(1);
        newsType.isEnabled = dataReader.GetBoolean(2);
    }
    dataReader.Close();
    return newsType;
}

額外多增加編輯畫面Edit.html
(跟Add.html一樣的Layout)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Edit NewsType</title>
    <link href="../css/bootstrap.min.css" rel="stylesheet" />
    <script src="../js/jquery/jquery.min.js"></script>
</head>
<body>
    <div style="padding:20px;border:1px solid #0094ff;width:600px;margin:30px;">
        <h3>新聞文章類別</h3>
        <hr />
        <div class="form-horizontal">
            <div class="form-group col-4">
                <label>文章類別</label>
                <input type="text" class="form-control" id="NewsTypeName">
            </div>
            <div class="form-group col-4">
                <label>是否啟用</label>
                <input type="checkbox" class="form-check" id="isEnabled">
            </div>
            <div class="form-group">
                <div class="col-md-2 col-md-10">
                    <button type="submit" id="btnSubmit" class="btn btn-primary">Submit</button>
                </div>
                <div>
                    <span id="msg" class="danger"></span>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        function getQueryGetParams(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var idxVar = 0; idxVar < vars.length; idxVar++) {
                var pair = vars[idxVar].split("=");
                if (pair[0] == variable)
                    return pair[1];
            }
            return "";
        }

        $(function () {
            var id = getQueryGetParams("id");
            $.ajax({
                type: "get",
                url: "/api/newstype/getbyid?id=" + id,
                dataType: "json",
                success: function (result) {
                    //console.log(result);
                    $("#NewsTypeName").val(result.newsTypeName);
                    $("#isEnabled").attr("checked", result.isEnabled);
                }
            });
        });

    </script>
</body>
</html>

藉由getQueryGetParams 取得get網址問號後面的key-value pair參數
取得特定news id後再去藉由Route Template "GetById" 呼叫
GetSpecificNewsTypeById 的api action method

https://ithelp.ithome.com.tw/upload/images/20210930/20107452CzBQOZRHik.png

https://ithelp.ithome.com.tw/upload/images/20210930/20107452dEl9RavByz.png

回填至編輯頁後再來就是提交PUT請求啦
如果還不知道PUT的請回去之前這篇看
.Net Core Web Api_筆記04_HTTP資源操作模式Put

在擴充一個put 的 更新用 action method

[HttpPut("Update")]
public ActionResult<int> UpdateNewsType(NewsType newsType)
{
    int RowCount = 0;
    if (newsType != null)
    {
        int enabled = (bool)newsType.isEnabled ? 1 : 0;
        string strSQL = @"update NewsType set NewsTypeName=@NewsTypeName , IsEnabled=@IsEnabled 
                            where NewsTypeId=@NewsTypeId ";
        Hashtable htParams = new Hashtable();
        htParams.Add("@NewsTypeId", newsType.NewsTypeId);
        htParams.Add("@NewsTypeName", newsType.NewsTypeName);
        htParams.Add("@IsEnabled", newsType.isEnabled);
        
        RowCount = MSSQLHelper.ExecuteNonQuery(strSQL, htParams);
    }
    return RowCount;
}

Edit.html 增加提交編輯更新的jQuery code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Edit NewsType</title>
    <link href="../css/bootstrap.min.css" rel="stylesheet" />
    <script src="../js/jquery/jquery.min.js"></script>
</head>
<body>
    <div style="padding:20px;border:1px solid #0094ff;width:600px;margin:30px;">
        <h3>新聞文章類別</h3>
        <hr />
        <div class="form-horizontal">
            <div class="form-group col-4">
                <label>文章類別</label>
                <input type="text" class="form-control" id="NewsTypeName">
            </div>
            <div class="form-group col-4">
                <label>是否啟用</label>
                <input type="checkbox" class="form-check" id="isEnabled">
            </div>
            <div class="form-group">
                <div class="col-md-2 col-md-10">
                    <button type="submit" id="btnSubmit" class="btn btn-primary">Submit</button>
                </div>
                <div>
                    <span id="msg" class="danger"></span>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        function getQueryGetParams(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var idxVar = 0; idxVar < vars.length; idxVar++) {
                var pair = vars[idxVar].split("=");
                if (pair[0] == variable)
                    return pair[1];
            }
            return "";
        }

        $(function () {
            var id = getQueryGetParams("id");
            $.ajax({
                type: "get",
                url: "/api/newstype/getbyid?id=" + id,
                dataType: "json",
                success: function (result) {
                    //console.log(result);
                    $("#NewsTypeName").val(result.newsTypeName);
                    $("#isEnabled").attr("checked", result.isEnabled);
                }
            });
        });

        $('#btnSubmit').click(function () {
            var id = getQueryGetParams("id");
            $.ajax({
                type: 'put',
                url: "/api/newstype/update",
                dataType: "text",
                data: JSON.stringify({
                    NewsTypeId: Number.parseInt(id),
                    NewsTypeName: $('#NewsTypeName').val(),
                    isEnabled: $('#isEnabled').prop('checked')
                }),
                contentType: 'application/json',
                success: function (result) {
                    if (result == "1") {
                        $('#msg').text('成功更新');
                    }
                }
            });
        });

    </script>
</body>
</html>

當我將生活類文章更新為啟用時候打到server-side的DTO isEnabled被turn true
DB中也成功更新

https://ithelp.ithome.com.tw/upload/images/20210930/20107452g8521cUbf9.png

https://ithelp.ithome.com.tw/upload/images/20210930/20107452SoCnWaoJ5k.png

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


上一篇
.Net Core Web Api_筆記15_api結合ADO.NET資料庫操作part3_資料刪除
系列文
.NET Core WebApi網頁應用開發16

尚未有邦友留言

立即登入留言