You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮未弹出exampleModalCenter弹窗,跳转至未定义的Employee/Edit路径

问题:点击Save按钮弹窗未显示,反而跳转至未定义的/Employee/Edit路径

问题现象

  • 点击id为Save的按钮,预期显示id为exampleModalCenter的弹窗
  • 实际页面跳转至localhost:/Employee/Edit,但该路径对应的Action方法并未在EmployeeController中定义

相关代码片段

EmployeeController关键代码(无Edit Action)

namespace AJAX.Controllers
{
    public class EmployeeController : Controller
    {
        // ... 其他代码

        // 仅定义Create Action,无Edit方法
        [Route("Employee/Create/{Id?}")]
        public async Task<IActionResult> Create(int? Id)
        {
            // ... 方法实现
        }

        // ... 其他代码
    }
}

绑定的jQuery点击事件

$("#Save").click(function () {
    debugger;
    $("#exampleModalCenter").modal('show');
    $("#exampleModalCenter").modal('show');
})

问题原因分析

  1. 按钮默认提交行为未阻止:Save按钮大概率是表单内的<button>或<input type="submit">,点击时会触发表单默认提交行为,导致页面跳转。
  2. 表单action属性错误:表单的action属性被设置为/Employee/Edit,但控制器中无对应Action,引发无效跳转。
  3. 事件绑定时机问题:若jQuery代码在DOM未加载完成时执行,会导致无法找到Save按钮,弹窗逻辑根本未触发。

解决方案

1. 阻止按钮默认提交行为

修改jQuery代码,添加event.preventDefault()阻断默认跳转逻辑:

$("#Save").click(function (event) {
    // 阻止表单默认提交
    event.preventDefault();
    $("#exampleModalCenter").modal('show');
})

2. 修正表单action属性

若表单需提交,将action指向控制器中存在的方法(如/Employee/AddEmployee);若无需提交,直接移除action属性:

<!-- 修正前 -->
<form action="/Employee/Edit" method="post">
<!-- 修正后(提交到正确Action) -->
<form action="/Employee/AddEmployee" method="post">
<!-- 无需提交时 -->
<form>

3. 确保事件正确绑定

将jQuery代码放在$(document).ready()中,确保DOM加载完成后再绑定事件:

$(document).ready(function() {
    $("#Save").click(function (event) {
        event.preventDefault();
        $("#exampleModalCenter").modal('show');
    });
});

4. 明确按钮类型

若使用<button>标签,默认类型为submit,会触发表单提交,改为button类型:

<button id="Save" type="button">保存</button>

内容的提问来源于stack exchange,提问作者Shashank Shetye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 03:45:52