iT邦幫忙

0

想請問刪除按鈕目前沒有反應,不知道是js的問題還是其他問題

  • 分享至 

  • xImage

想請問刪除按鈕目前沒有反應,不知道是js的問題還是Controller的問題又或者是html的按鈕部分寫錯

有註解的地方是我今天寫得但不太了解到底哪裡出問題
先提供html的index部分給各位參考

@using TrainingWebMVC.Models.DBModel;
@using X.PagedList;
@using static TrainingWebMVC.Areas.Admin.Controllers.TrainingController;
@model ViewTrainingIndex;

   
<script type="text/javascript">
    $(function () {
        //查詢
        $("#search").on('click', function () {
            $("#trainingForm").submit();
        });


        $("select[name='itemPageNumber']").change(function () { 

            var selectedPage = $(this).val(); 
            $("input[name='pageNumber']").val(selectedPage); 
            $("#trainingForm").submit();  

            console.log($(this).val());  
       
            $("button[name='deleteBtn']").click(function () {   // 刪除js
                let trainingTextId = $(this).siblings("input[name='trainingTextid']").val();

                if (confirm("是否確定刪除")) {
                    $.ajax({
                        type: 'POST',
                        url: '@Url.Action("Removed", "Training", new { area = "Admin"})',
                        data: { id: trainingTextId }, 
                        success: function (result) {
                            result = JSON.parse(result);
                            if (result.success) {
                                alert(result.message);
                            } else {
                                alert(result.message);
                            }
                            window.location.href = '/Admin/Index';
                        }
                    });
                }
            });
</script>



    <div class="container-fluid">                   
        <!-- -------------------------------------------------------------- -->
        <!-- Start Page Content -->
        <!-- -------------------------------------------------------------- -->
        <div class="row">                                                        
            <div class="col-12">
                <!-- ----------------------------------------- -->
                <!-- 1. Basic Form -->
                <!-- ----------------------------------------- -->
                <div class="card">                                            
                    <div class="card-body">
                        <h4 class="card-title">查詢條件</h4>
                    <form id="trainingForm" action="@Url.Action("Index","Training",new {Area="Admin"})" method="get">    
                        <input type="hidden" name="pageNumber" value="@Model.trainingTextPageds.PageNumber" />
                            <div class="form-body">
                                <div class="row">
                                    <label for="example-text-input" class="col-md-4 text-end">文字類型 : </label>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                        <select name="textType" aria-controls="zero_config" class="form-select">
                                            <option value=" ">請選擇</option> 
                                            <option value="公司名稱" @((Model.criteria.textType == "公司名稱" ? "selected" : ""))>公司名稱</option> 
                                            <option value="非法⼈團體" @((Model.criteria.textType == "非法⼈團體" ? "selected" : ""))>非法⼈團體</option>
                                            <option value="機關" @((Model.criteria.textType == "機關" ? "selected" : ""))>機關</option>
                                            <option value="學校" @((Model.criteria.textType == "學校" ? "selected" : ""))>學校</option>
                                            <option value="商號" @((Model.criteria.textType == "商號" ? "selected" : ""))>商號</option>
                                            <option value="寺廟" @((Model.criteria.textType == "寺廟" ? "selected" : ""))>寺廟</option>
                                            <option value="診所" @((Model.criteria.textType == "診所" ? "selected" : ""))>診所</option>
                                            <option value="⾃然⼈之姓名" @((Model.criteria.textType == "⾃然⼈之姓名" ? "selected" : ""))>⾃然⼈之姓名</option>
                                            <option value="年⽉⽇" @((Model.criteria.textType == "年⽉⽇" ? "selected" : ""))>年⽉⽇</option>
                                            <option value="國⺠⾝分證統⼀編號" @((Model.criteria.textType == "國⺠⾝分證統⼀編號" ? "selected" : ""))>國⺠⾝分證統⼀編號</option>
                                            <option value="婚姻" @((Model.criteria.textType == "婚姻" ? "selected" : ""))>婚姻</option>
                                            <option value="聯絡⽅式" @((Model.criteria.textType == "聯絡⽅式" ? "selected" : ""))>聯絡⽅式</option>
                                            <option value="書名" @((Model.criteria.textType == "書名" ? "selected" : ""))>書名</option>
                                            <option value="網站名稱" @((Model.criteria.textType == "網站名稱" ? "selected" : ""))>網站名稱</option>
                                            <option value="網址" @((Model.criteria.textType == "網址" ? "selected" : ""))>網址</option>
                                            <option value="餐廳名稱" @((Model.criteria.textType == "餐廳名稱" ? "selected" : ""))>餐廳名稱</option>
                                        </select>
                                        </div>
                                    </div>
                                </div>
                            <div class="row">
                                <label for="example-text-input" class="col-md-4 text-end">文字內容 : </label>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <input class="form-control" type="text" name="content" value="@Model.criteria.content" id="example-text-input">
                                    </div>                              
                                </div>
                            </div>
                            <div class="row">
                                <label for="example-text-input" class="col-md-4 text-end">建立者 : </label>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <input class="form-control" type="text" name="creator" value="@Model.criteria.creator" id="example-text-input">
                                    </div>                             
                                </div>
                            </div>
                        </div>
                            <div class="form-actions mt-4">
                                <div class="text-center">
                                    <a class="btn waves-effect waves-light btn-rounded btn-success" id="search">查詢</a>
                                <a href="@Url.Action("Edit", "Training", new { area = "Admin", id = "add" })" class="btn waves-effect waves-light btn-rounded btn-warning">新增</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <!-- striped table -->
        <div class="row">                           
            <div class="col-12">
                <div class="card">                   
                    <div class="card-body">                
                        <h4 class="card-title">查詢結果</h4>                        
                        <h6 class="card-subtitle lh-base"></h6>                        
                    </div>
                    <div class="table-responsive">
                        <table class="table customize-table table-striped mb-0 v-middle">
                            <thead>
                                <tr>
                                <th class="border-bottom border-top">文字類型</th>   
                                <th class="border-bottom border-top">文字內容</th>
                                <th class="border-bottom border-top">建立者</th>
                                <th class="border-bottom border-top"></th>
                                <th class="border-bottom border-top"></th>
                                <th class="border-bottom border-top">功能</th>
                                </tr>
                            </thead>
                            <tbody>
                            @{
                                foreach (TrainingText trainingText in Model.trainingTextPageds.ToList())
                                { 
                                        <tr>
                                            <td>
                                            <div class="d-flex align-items-center">                                                                                                  
                                                    <span class="ms fw-normal">@trainingText.textType</span>
                                                </div>
                                            </td>
                                        <td>@trainingText.content</td> 
                                            <td>@trainingText.creator</td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                </div>
                                            </td>
                                            <td></td>
                                            <td>
                                            <a href="@Url.Action("Edit", "Training", new { area = "Admin", id = trainingText.id })" class="btn waves-effect waves-light btn-rounded btn-warning">修改</a>
 <!--刪除  -->                               <button type="submit" class="btn waves-effect waves-light btn-rounded btn-danger" name="deleteBtn">刪除</button>
 <!--  刪除-->                               <input type="hidden" name="trainingText.id" value="@trainingText.id" />
                                            <!-- Url.Action("Removed", "Training", new { area = "Admin", id = trainingText.id })-->

                                            
                                            </td>
                                        </tr>
                                }
                            }
                        </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="row pure-g pagination" style="margin-left:20px">
            <div class="col pageInfo">
                共有<span id="totalCount" class="txtRed01">@Model.trainingTextPageds.TotalItemCount</span>筆, 
                每頁<span id="pageCount" class="txtRed01">@Model.trainingTextPageds.PageSize</span>筆,  
                共有<span id="totalPage" class="txtRed01">@Model.trainingTextPageds.PageCount</span>頁, 
                目前在第<span id="nowPage" class="txtRed01">@Model.trainingTextPageds.PageNumber</span>頁,  
                                                                             
                (跳至第
                    <select name='itemPageNumber'>                   
                    @for (int i = 1; i <= Model.trainingTextPageds.PageCount; i++)  
                    {                        
                        <option value="@i" @(i == Model.criteria.pageNumber ? "selected" : "")>@i</option>
                    }
                    </select>
                    頁)
                </div>
            </div>
        </div>
    </div>


然後再來是Controller的部分

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using TrainingWebMVC.Models.DBModel;
using TrainingWebMVC.Services.DbServices;
using X.PagedList;
using static TrainingWebMVC.Managers.DbManagers.TrainingTextManager;

namespace TrainingWebMVC.Areas.Admin.Controllers
{
    [Area(areaName: "Admin")]
    public class TrainingController : Controller
    {
        private readonly TrainingTextService trainingTextService;
        private readonly ILogger<TrainingController> logger;    //多寫這行
        public TrainingController(TrainingTextService _trainingTextService, ILogger<TrainingController> _logger)  //多寫逗號以後的
        {
            this.trainingTextService = _trainingTextService;
            logger = _logger;                                      //多寫這行
        }
        public async Task<IActionResult> Index(string textType, string content, string creator, int pageNumber = 1)
        {
            int pagesize = 10;

            TrainingTextService.Criteria criteria = new Criteria();

            criteria.textType = textType;
            criteria.content = content;
            criteria.creator = creator;
            criteria.pageNumber = pageNumber;
            int pagecurrent = criteria.pageNumber ?? 1;

            IPagedList<TrainingText> trainingTextPageds = await trainingTextService.ExcuteQuery(criteria).OrderByDescending(m => m.createDate).ToPagedListAsync(pagecurrent, pagesize);

            ViewTrainingIndex viewTrainingIndex = new ViewTrainingIndex();
            viewTrainingIndex.criteria = criteria;
            viewTrainingIndex.trainingTextPageds = trainingTextPageds;

            return View(viewTrainingIndex);
        }

        public class ViewTrainingIndex
        {
            public TrainingTextService.Criteria? criteria;
            public IPagedList<TrainingText>? trainingTextPageds;
        }
        [HttpGet]
        public IActionResult Edit(int id)
        {
            TrainingText? trainingTextToEdit = null;


            if (id > 0)
                trainingTextToEdit = trainingTextService.GetById(id);

            if (trainingTextToEdit == null)
            {
                trainingTextToEdit = new TrainingText();
            }
            return View(trainingTextToEdit);
        }
        //action removed
        public async Task<IActionResult> Removed(long? id)     //此部分為Removed
        {
            Dictionary<String, Object> valueObject = new();

            if (id is not null && id > 0)
            {
                try
                {
                    TrainingText? trainingTextToEdit = await trainingTextService.GetByIdAsync(id.Value, true);
                    if (trainingTextToEdit == null)
                    {
                        valueObject.Add("success", false);
                        valueObject.Add("message", "找不到此筆資料");
                    }
                    else
                    {
                        await trainingTextService.RemovedAsync(id.Value);
                        valueObject.Add("success", true);
                        valueObject.Add("message", "刪除成功");
                    }
                }
                catch (Exception ex)
                {
                    valueObject.Add("success", false);
                    valueObject.Add("message", ex.Message);
                    logger.LogError(ex, "message:{message}", ex.Message);
                }
            }
            return Json(valueObject);
        }


        [HttpPost]
        public IActionResult Edit(int id, string textType, string content, string creator)
        {
            TrainingText? trainingTextToEdit;

            if (id == 0)
            {
                trainingTextToEdit = new TrainingText
                {
                    createDate = DateTime.Now,
                    enterpriseId = 1,
                    departmentId = 1,
                    modifyDate = null,
                    modifier = "admin",
                    removed = false,
                    textType = textType,
                    content = content,
                    creator = creator
                };
                trainingTextService.Save(trainingTextToEdit);
            }
            else
            {
                trainingTextToEdit = trainingTextService.GetById(id, true);
                if (trainingTextToEdit == null)
                {
                    trainingTextToEdit = new TrainingText();
                }
                else
                {
                    trainingTextToEdit.modifyDate = DateTime.Now;
                    trainingTextToEdit.textType = textType;
                    trainingTextToEdit.content = content;
                    trainingTextToEdit.creator = creator;
                    trainingTextService.Save(trainingTextToEdit);
                }
            }
            return View(trainingTextToEdit);
        }
    }
}

我自己有再想會不會是html的刪除input裡面的value我帶錯

我附上Controller程式碼截圖吧,放我今天寫的部分以及重要的部分就好勞煩各位眼睛了
https://ithelp.ithome.com.tw/upload/images/20231004/2016361589Fb2a2Z9h.png
https://ithelp.ithome.com.tw/upload/images/20231004/20163615K6WTSnAxLk.png
上圖畫線是今天增加為了刪除寫的

https://ithelp.ithome.com.tw/upload/images/20231004/2016361594pMwRJXoK.png
上圖圍刪除部分

然後是html裡index的截圖
https://ithelp.ithome.com.tw/upload/images/20231004/20163615t7qccuXyIB.png
https://ithelp.ithome.com.tw/upload/images/20231004/20163615rQt3oaYtlH.png
https://ithelp.ithome.com.tw/upload/images/20231004/20163615IJJ9AbA8Dt.png

附上F12的Console
https://ithelp.ithome.com.tw/upload/images/20231004/201636157lyfPoW8M8.png

看更多先前的討論...收起先前的討論...
wdchiang iT邦新手 2 級 ‧ 2023-10-04 17:14:07 檢舉
Chrome -> F12 -> Console 可以看到錯誤訊息。
感謝你!!我其實已經看過了忘記附上截圖,感覺還是沒看出甚麼問題
wdchiang iT邦新手 2 級 ‧ 2023-10-04 17:39:14 檢舉
646 點下去,那段程式有錯。
不給點
wdchiang iT邦新手 2 級 ‧ 2023-10-04 17:44:51 檢舉
你那邊有語法錯誤,導致網頁沒辦法正常執行。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
wdchiang
iT邦新手 2 級 ‧ 2023-10-04 17:41:19
 <!--刪除  -->                               <button type="submit" class="btn waves-effect waves-light btn-rounded btn-danger" name="deleteBtn">刪除</button>
 
改成

 <!--刪除  -->                               <button type="button" class="btn waves-effect waves-light btn-rounded btn-danger" name="deleteBtn">刪除</button>
看更多先前的回應...收起先前的回應...

沒有差耶

wdchiang iT邦新手 2 級 ‧ 2023-10-04 17:59:51 檢舉

正常的寫法,type="button"

https://ithelp.ithome.com.tw/upload/images/20231004/20017157FZsZ7Pfuxb.png

你那邊有語法錯誤,導致網頁沒辦法正常執行。

其實是JS少一個括號 = = 不過新問題也出現了
某筆資料按刪除後F12會出現以下錯誤
我覺得前三行才是最主要錯誤

Uncaught SyntaxError: "[object Object]" is not valid JSON
    at JSON.parse (<anonymous>)
    at Object.success (Index:633:39)
    at u (jquery.min.js:2:27457)
    at Object.fireWith [as resolveWith] (jquery.min.js:2:28202)
    at k (jquery.min.js:2:77651)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2:79907)
success @ Index:633
u @ jquery.min.js:2
fireWith @ jquery.min.js:2
k @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
load (async)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ Index:628
dispatch @ jquery.min.js:2
y.handle @ jquery.min.js:2

然後畫面資料沒有刪除要網頁重新整理那一筆才會刪除,但重點資料庫資料還在Zzz..

wdchiang iT邦新手 2 級 ‧ 2023-10-05 10:32:32 檢舉

不知道哪裡錯,就下 debugger; Chrome 按 F12 逐步 trace。

0
janlin002
iT邦好手 1 級 ‧ 2023-10-04 17:47:09

這個排版...
看得我頭好暈

有確定吃到 JQuery 的程式碼了嗎?

我附上截圖了,感謝

我要發表回答

立即登入回答