iT邦幫忙

2021 iThome 鐵人賽

2
自我挑戰組

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

.Net Core Web Api_筆記17_api結合ADO.NET資料庫操作part5_新聞文章新增_新聞類別元素透過API綁定方式

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20211223/201074521MCjNNwR8U.png

有了新聞類別相關的增刪改查後
就要來進行新聞文章的增刪改查功能導入

新建好NewsController

wwwroot下額外建立News目錄
並新增添加新聞文章的頁面表單
Add.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Add News</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 #ccc;width:600px;margin:30px;">
        <h3>新增新聞文章</h3>
        <hr />
        <div class="form-horizontal">
            <div class="form-group col-8">
                <label>新聞標題:</label>
                <input type="text" id="NewsTitle" class="form-control" />
            </div>
            <div class="form-group col-8">
                <label>新聞內容:</label>
                <textarea id="NewsContent" class="form-control"></textarea>
            </div>
            <div class="form-group col-8">
                <label>新聞分類:</label>
                <select id="NewsTypeId"></select>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" id="savebtn" value="保存" class="btn btn-primary" />                    
                </div>
                <div>
                    <span id="msg" class="bg-danger"></span>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "get",
                url: "/api/newstype/show",
                dataType: "json",
                success: function (result) {
                    var opt = "";
                    $.each(result, function (n, value) {
                        opt += "<option id='" + value.newsTypeId + "'>" + value.newsTypeName + "</option>";
                    });
                    $("#NewsTypeId").append(opt);
                }
            });


        });
    </script>
</body >
</html >

在網頁UI元素中時常會需要透過跟DB動態撈取出來的資料作綁定

以這邊微粒就是要綁定下拉選單的新聞類別
藉由jQuery呼叫後端API方式GET查出並綁定

https://ithelp.ithome.com.tw/upload/images/20211223/20107452w15IdXKMi5.png

在此完善我們的NewsController
新增insert新聞文章的Action

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

namespace MyNet5ApiAdoTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NewsController : ControllerBase
    {

        [HttpPost("Add")]
        public ActionResult<int> AddNewsInfo(NewsInfo newsInfo)
        {
            int RowCount = 0;
            if (newsInfo == null)
                return NotFound();

            string strSQL = @"INSERT INTO NewsInfo (NewsTitle,NewsContent,CreateDate,NewsTypeId) 
                                  VALUES (@NewsTitle,@NewsContent,@CreateDate,@NewsTypeId) ";
            Hashtable htParams = new Hashtable();
            htParams.Add("@NewsTitle", newsInfo.NewsTitle);
            htParams.Add("@NewsContent", newsInfo.NewsContent);
            //htParams.Add("@CreateDate", newsInfo.CreateDate);
            htParams.Add("@CreateDate", DateTime.Now);
            htParams.Add("@NewsTypeId", newsInfo.NewsTypeId);
            RowCount = MSSQLHelper.ExecuteNonQuery(strSQL, htParams);
            return RowCount;
        }

    }
}

Add.html前端部分也增加Ajax呼叫

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Add News</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 #ccc;width:600px;margin:30px;">
        <h3>新增新聞文章</h3>
        <hr />
        <div class="form-horizontal">
            <div class="form-group col-8">
                <label>新聞標題:</label>
                <input type="text" id="NewsTitle" class="form-control" />
            </div>
            <div class="form-group col-8">
                <label>新聞內容:</label>
                <textarea id="NewsContent" class="form-control"></textarea>
            </div>
            <div class="form-group col-8">
                <label>新聞分類:</label>
                <select id="NewsTypeId"></select>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" id="savebtn" value="保存" class="btn btn-primary" />                    
                </div>
                <div>
                    <span id="msg" class="bg-danger"></span>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "get",
                url: "/api/newstype/show",
                dataType: "json",
                success: function (result) {
                    var opt = "";
                    $.each(result, function (n, value) {
                        opt += "<option id='" + value.newsTypeId + "'>" + value.newsTypeName + "</option>";
                    });
                    $("#NewsTypeId").append(opt);
                }
            });

            $("#savebtn").click(function () {
                $.ajax({
                    type: "post",
                    url: "/api/news/add",
                    dataType: "text",
                    data: JSON.stringify({
                        Id: 1,
                        NewsTitle: $("#NewsTitle").val(),
                        NewsContent: $("#NewsContent").val(),
                        newsTypeId:  Number.parseInt($("#NewsTypeId").find("option:selected").attr("id"))
                    }),
                    contentType: "application/json",
                    success: function (result) {
                        if (result == '1') {
                            $("#msg").text("新增成功!");
                        }
                    }
                });
            });
        });
    </script>
</body >
</html >

這裡我們就隨意挑一篇新聞文章來嘗試新增
https://www.economic-news.tw/2020/11/investment.html

https://ithelp.ithome.com.tw/upload/images/20211223/20107452EH7OVOj3Pb.png

https://ithelp.ithome.com.tw/upload/images/20211223/20107452Z36Zp7lhja.png

https://ithelp.ithome.com.tw/upload/images/20211223/20107452dSVGM4f8pa.png

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


上一篇
.Net Core Web Api_筆記16_api結合ADO.NET資料庫操作part4_資料編輯提交更新
下一篇
.Net Core Web Api_筆記18_api結合ADO.NET資料庫操作part6_新聞文章表格陳列查詢
系列文
.NET Core WebApi網頁應用開發25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言