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

MVC合并Add/Edit硬件视图后添加表单无法提交问题排查

问题排查:合并Add/Edit硬件页面后Save按钮无响应

问题描述

原本有AddHardware和EditHardware两个独立页面,分别负责硬件信息的添加与编辑。为减少代码重复合并为一个页面后,编辑模式下的Update按钮正常工作,但添加模式下的Save按钮点击无任何反应,怀疑是JavaScript存在重复定义问题。

合并后的Razor代码

@using (Html.BeginForm("AddEditInvHardware", "InvHardware", FormMethod.Post, new { @class = "form-horizontal", id = "HardwareForm" }))
{         
    if (Model != null && Model.InvHardwareID > 0)
    {
        <div style="float:right; padding-inline:12px;">
            <input type="button" value="Update" id="Submit" class="btn btn-primary btn-lg" onclick="onSubmit()" style="font-size: 15px; font-family: Verdana, Geneva, Tahoma, sans-serif" />
            <input type="button" value="Cancel" id="Submit" class="btn btn-primary btn-lg" onclick="history.go(-1);" href="javascript:void(0);" style="font-size: 15px; font-family: Verdana, Geneva, Tahoma, sans-serif" />
        </div>
        <hr width="100%" style="border:hidden" />
    }
    else
    {
        <div style="float:right; padding-inline:12px;">                     
            <input type="button" value="Save" id="Submit" class="btn btn-primary btn-lg" onclick="onSubmit()" style="font-size: 15px; font-family: Verdana, Geneva, Tahoma, sans-serif" />
            @Html.ActionLink("Cancel", "InvHardware", "InvHardware", new { @class = "btn btn-primary btn-lg", @style = "font-size: 15px; font-family: Verdana, Geneva, Tahoma, sans-serif" })
        </div>
        <hr width="100%" style="border:hidden" />
    }
}

对应JavaScript代码

<script type="text/javascript">
    $(document).ready(function () {

        SetDateLabelsPurchaseOrLease();

        $("#AcquisitionTypeID").change(function () {
            SetDateLabelsPurchaseOrLease();
        });

        function SetDateLabelsPurchaseOrLease() {
            myAcqType = $('#AcquisitionTypeID').val();
            if (myAcqType == 1) {
                var myStartDate = "Warranty Start Date";
                var myEndDate = "Warranty End Date";
            }
            if (myAcqType == 2) {
                var myStartDate = "Leased Start Date";
                var myEndDate = "Leased End Date";
            }
            $('#LabelForWL_StartDate').html(myStartDate);
            $('#LabelForWL_EndDate').html(myEndDate);
        }

        $("#WL_StartDate").attr("autocomplete", "off");
        $(function () {
            $("#WL_StartDate").datepicker({
                changeMonth: true,
                changeYear: true,
                onSelect: function (selected) {
                    $("#WL_EndDate").datepicker("option", "minDate", selected)
                },
            });
        });

        $("#WL_EndDate").attr("autocomplete", "off");
        $(function () {
            $("#WL_EndDate").datepicker({
                changeMonth: true,
                changeYear: true,
                onSelect: function (selected) {
                    $("#WL_StartDate").datepicker("option", "maxDate", selected)
                },
            });
        });

        $("#ReceivedDate").attr("autocomplete", "off");
        $(function () {
            $("#ReceivedDate").datepicker({
                maxDate: '0',
                changeMonth: true,
                changeYear: true,
            });
        });

        $('#departments-data-table').DataTable({
            columnDefs: [{
                "targets": [6],
                "searchable": false,
                "targets": [6],
                "orderable": false
            }]
        });
    });
    function onSubmit() {
        var myAcqType = $('#AcquisitionTypeID').val();
        Alert("myAcqType", myAcqType);
        if (PassValidations() == true) {
            $('#HardwareForm').submit();               
        }
        //else do nothing
    }
    function PassValidations() {
        try {
            alert("Begin PassValidations", "");
            ClearErrorCodesOnPage();

            var startDate = $('#WL_StartDate').val(),
                endDate = $('#WL_EndDate').val(),
                recDate = $('#ReceivedDate').val(),
                amount = $('#Amount').val(),
                sdate = new Date(startDate),
                edate = new Date(endDate),
                rdate = new Date(recDate);

            var myB5 = ValidateDateTextBox("ReceivedDate", "Received Date");
            var myB6 = ValidateDateTextBox("WL_StartDate", "Start Date");
            var myB7 = ValidateDateTextBox("WL_EndDate", "End Date");
            var myB8 = ValidateTwoDateTextBox("WL_StartDate", "WL_EndDate", "Start Date");
            var myB9 = ValidateNoFutureDateTextBox("ReceivedDate", "Received Date");

            var myB1 = ValidateBlankTextBox("Amount", "Amount");
            var myB2 = ValidateBlankTextBox("ReceivedDate", "Received Date");
            var myB3 = ValidateBlankTextBox("WL_StartDate", "Start Date");
            var myB4 = ValidateBlankTextBox("WL_EndDate", "End Date");

            var myB10 = ValidateBlankTextBox("PONumber", "PO Number");
            var myB11 = ValidateBlankTextBox("Equipment", "Equipment");
            var myB12 = ValidateBlankTextBox("SerialNum", "Serial #");
            var myB13 = ValidateBlankTextBox("HardwareModel", "Model");
            var myB14 = ValidateBlankTextBox("AssetNum", "Asset #");
            var myb15 = ValidateBlankTextBox("Manufacturer", "Manufacturer");

            if (
                myB1
                && myB2
                && myB3
                && myB4
                && myB5
                && myB6
                && myB7
                && myB8
                && myB9
                && myB10
                && myB11
                && myB12
                && myB13
                && myB14
                && myb15
            ) {
                alert("Pass PassValidations", "true");
                return true;
            } else {
                //alert("Failed");
                alert("Not Pass PassValidations", "false");
                return false;
            }
        } catch (err) {
            document.getElementById("demo").innerHTML = err.message;
        }
    }

    function ClearErrorCodesOnPage() {
        alert("begin Clear Codes");
        $('#errorAmount').html("");
        $("#errorAmount").css("display", "none");
        $('#errorReceivedDate').html("");
        $("#errorReceivedDate").css("display", "none");
        $('#errorWL_StartDate').html("");
        $("#errorWL_StartDate").css("display", "none");
        $('#errorWL_EndDate').html("");
        $("#errorWL_EndDate").css("display", "none");

        $('#errorPONumber').html("");
        $("#errorPONumber").css("display", "none");
        $('#errorEquipment').html("");
        $("#errorEquipment").css("display", "none");
        $('#errorSerialNum').html("");
        $("#errorSerialNum").css("display", "none");
        $('#errorHardwareModel').html("");
        $("#errorHardwareModel").css("display", "none");
        $('#errorAssetNum').html("");
        $("#errorAssetNum").css("display", "none");
        $('#errorManufacturer').html("");
        $("#errorManufacturer").css("display", "none");
        alert("end Clear Codes");
    }
</script>

问题根源分析

  1. 重复ID冲突:Razor代码中,Update和Save按钮的ID均为Submit,HTML要求ID必须唯一。浏览器只会为第一个匹配ID的元素绑定事件,导致添加模式下的Save按钮事件无法触发。
  2. JavaScript拼写错误:onSubmit函数中使用了Alert(大写A),而原生JavaScript弹窗函数是alert(小写a),这会直接抛出错误,中断后续代码执行。
  3. 冗余DOM就绪函数:代码中多次嵌套$(function(){}),虽然不影响功能,但会增加代码冗余度。

修复方案

1. 修复重复ID问题

将两个提交按钮的ID改为唯一值,或直接去掉ID,通过class绑定事件(更推荐):

@using (Html.BeginForm("AddEditInvHardware", "InvHardware", FormMethod.Post, new { @class = "form-horizontal", id = "HardwareForm" }))
{         
    if (Model != null && Model.InvHardwareID > 0)
    {
        <div style="float:right; padding-inline:12px;">
            <input type="button" value="Update" class="btn btn-primary btn-lg submit-btn" style="font-size: 15px; font-family: Verdana, Geneva, Tahoma, sans-serif" />
            <input type="button" value="Cancel" class="btn btn-primary btn-lg" onclick="history.go(-1);" href="javascript:void(0);" style="font-size: 15px; font-family: Verdana, Geneva, Tahoma, sans-serif" />
        </div>
        <hr width="100%" style="border:hidden" />
    }
    else
    {
        <div style="float:right; padding-inline:12px;">                     
            <input type="button" value="Save" class="btn btn-primary btn-lg submit-btn" style="font-size: 15px; font-family: Verdana, Geneva, Tahoma, sans-serif" />
            @Html.ActionLink("Cancel", "InvHardware", "InvHardware", new { @class = "btn btn-primary btn-lg", @style = "font-size: 15px; font-family: Verdana, Geneva, Tahoma, sans-serif" })
        </div>
        <hr width="100%" style="border:hidden" />
    }
}

2. 修正JavaScript拼写错误

将Alert改为alert,并调整参数格式(原生alert仅支持一个参数):

function onSubmit() {
    const myAcqType = $('#AcquisitionTypeID').val();
    alert("myAcqType: " + myAcqType);
    if (PassValidations()) {
        $('#HardwareForm').submit();               
    }
}

3. 优化事件绑定与代码结构

用jQuery事件委托替代内联onclick,并简化冗余代码:

$(document).ready(function () {
    // ... 其他代码保持不变 ...

    // 用class绑定提交事件
    $('.submit-btn').click(function() {
        onSubmit();
    });
});

最终修复后的完整JavaScript代码

<script type="text/javascript">
    $(document).ready(function () {
        SetDateLabelsPurchaseOrLease();

        $("#AcquisitionTypeID").change(function () {
            SetDateLabelsPurchaseOrLease();
        });

        function SetDateLabelsPurchaseOrLease() {
            const myAcqType = $('#AcquisitionTypeID').val();
            let myStartDate, myEndDate;
            if (myAcqType == 1) {
                myStartDate = "Warranty Start Date";
                myEndDate = "Warranty End Date";
            } else if (myAcqType == 2) {
                myStartDate = "Leased Start Date";
                myEndDate = "Leased End Date";
            }
            $('#LabelForWL_StartDate').html(myStartDate);
            $('#LabelForWL_EndDate').html(myEndDate);
        }

        // 简化日期选择器初始化
        $("#WL_StartDate").attr("autocomplete", "off").datepicker({
            changeMonth: true,
            changeYear: true,
            onSelect: function (selected) {
                $("#WL_EndDate").datepicker("option", "minDate", selected)
            },
        });

        $("#WL_EndDate").attr("autocomplete", "off").datepicker({
            changeMonth: true,
            changeYear: true,
            onSelect: function (selected) {
                $("#WL_StartDate").datepicker("option", "maxDate", selected)
            },
        });

        $("#ReceivedDate").attr("autocomplete", "off").datepicker({
            maxDate: '0',
            changeMonth: true,
            changeYear: true,
        });

        $('#departments-data-table').DataTable({
            columnDefs: [{
                "targets": [6],
                "searchable": false,
                "orderable": false
            }]
        });

        // 绑定提交按钮事件
        $('.submit-btn').click(function() {
            onSubmit();
        });
    });

    function onSubmit() {
        const myAcqType = $('#AcquisitionTypeID').val();
        alert("myAcqType: " + myAcqType);
        if (PassValidations()) {
            $('#HardwareForm').submit();               
        }
    }

    function PassValidations() {
        try {
            alert("Begin PassValidations");
            ClearErrorCodesOnPage();

            const startDate = $('#WL_StartDate').val(),
                  endDate = $('#WL_EndDate').val(),
                  recDate = $('#ReceivedDate').val(),
                  amount = $('#Amount').val(),
                  sdate = new Date(startDate),
                  edate = new Date(endDate),
                  rdate = new Date(recDate);

            const myB5 = ValidateDateTextBox("ReceivedDate", "Received Date");
            const myB6 = ValidateDateTextBox("WL_StartDate", "Start Date");
            const myB7 = ValidateDateTextBox("WL_EndDate", "End Date");
            const myB8 = ValidateTwoDateTextBox("WL_StartDate", "WL_EndDate", "Start Date");
            const myB9 = ValidateNoFutureDateTextBox("ReceivedDate", "Received Date");

            const myB1 = ValidateBlankTextBox("Amount", "Amount");
            const myB2 = ValidateBlankTextBox("ReceivedDate", "Received Date");
            const myB3 = ValidateBlankTextBox("WL_StartDate", "Start Date");
            const myB4 = ValidateBlankTextBox("WL_EndDate", "End Date");

            const myB10 = ValidateBlankTextBox("PONumber", "PO Number");
            const myB11 = ValidateBlankTextBox("Equipment", "Equipment");
            const myB12 = ValidateBlankTextBox("SerialNum", "Serial #");
            const myB13 = ValidateBlankTextBox("HardwareModel", "Model");
            const myB14 = ValidateBlankTextBox("AssetNum", "Asset #");
            const myb15 = ValidateBlankTextBox("Manufacturer", "Manufacturer");

            const isValid = myB1 && myB2 && myB3 && myB4 && myB5 && myB6 && myB7 && myB8 && myB9 && myB10 && myB11 && myB12 && myB13 && myB14 && myb15;
            
            alert(isValid ? "Pass PassValidations: true" : "Not Pass PassValidations: false");
            return isValid;
        } catch (err) {
            document.getElementById("demo").innerHTML = err.message;
            return false;
        }
    }

    function ClearErrorCodesOnPage() {
        alert("begin Clear Codes");
        // 批量清空错误提示
        const errorElements = [
            '#errorAmount', '#errorReceivedDate', '#errorWL_StartDate', '#errorWL_EndDate',
            '#errorPONumber', '#errorEquipment', '#errorSerialNum', '#errorHardwareModel',
            '#errorAssetNum', '#errorManufacturer'
        ];
        
        errorElements.forEach(selector => {
            $(selector).html("").css("display", "none");
        });
        alert("end Clear Codes");
    }
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:44:56