如何有条件地阻止使用 server-side/code-behind 提交表单?

How can I conditionally prevent a form from submitting with server-side/code-behind?

当我的 "submit"(保存)按钮被点击时,它所做的一件事是验证两个 "totals" 值是否匹配,如果不匹配,returns有红色 'bad boy!' 消息的用户:

message = new LiteralControl();
AddVerticalSpace();
Controls.Add(message);
decimal? paymentTot = TryConvertToDecimal(boxPaymentAmount.Text);
if ((null == paymentTot) || (paymentTot < 0))
{
    paymentTot = 0M;
}
decimal? grandTot = TryConvertToDecimal(boxGrandTotal.Text);
if ((null == grandTot) || (grandTot < 0))
{
    grandTot = 0M;
}
if (grandTot != paymentTot)
{
    AddVerticalSpace();
    message.Text = "<span style='color:red'>Total and Payment Total do not match; Please enter the same amount for both values and try again.</span>";
    return;
}

我对 "return" 的意图是提交被中止;然而,使用上面的代码,表单仍然被提交 - 它恢复到它的初始 appearance/state。如何有条件地阻止这种自动提交行为?

更新

这是给泰瑞·杰克逊的:

这是服务器端保存按钮。首先,它是有条件地动态创建和配置的:

if (AnyCheckboxSelected())
{
    // Create Save button
    this.Controls.Add(new LiteralControl("<br />"));
    btnSave = new Button();
    btnSave.ID = "btnSave";
    btnSave.Text = "Save";
    btnSave.Click += new EventHandler(btnSave_Click);
    this.Controls.Add(btnSave);

    AddVerticalSpace();
}

...这是事件处理程序:

protected void btnSave_Click(object sender, EventArgs e)
{
    LiteralControl message = null;
    try
    {
        fullAddressChosen = rbFullAddress.Checked;
        paymentToAnIndividualDropDownChosen = rbPaymentToIndividual.Checked;
        paymentToAVendorDropDownChosen = rbPaymentToVendor.Checked;

        message = new LiteralControl();
        AddVerticalSpace();
        Controls.Add(message);
        decimal? paymentTot = TryConvertToDecimal(boxPaymentAmount.Text);
        if ((null == paymentTot) || (paymentTot < 0))
        {
            paymentTot = 0M;
        }
        decimal? grandTot = TryConvertToDecimal(boxGrandTotal.Text);
        if ((null == grandTot) || (grandTot < 0))
        {
            grandTot = 0M;
        }
        if (grandTot != paymentTot)
        {
            AddVerticalSpace();
            message.Text = "<span style='color:red'>Total and Payment Total do not match; Please enter the same amount for both values and try again.</span>";
            return;
        }
        ConditionallyCreateList();
        SaveInputToList();
        listOfListItems = ReadFromList();
        message.Text = "Saving the data has been successful";

        // Re-visiblize any rows with vals
        if (RowContainsVals(3))
        {
            foapalrow3.Style["display"] = "table-row";
        }
        if (RowContainsVals(4))
        {
            foapalrow4.Style["display"] = "table-row";
        }
        if (RowContainsVals(5))
        {
            foapalrow5.Style["display"] = "table-row";
        }
        if (RowContainsVals(6))
        {
            foapalrow6.Style["display"] = "table-row";
        }

        AddVerticalSpace();

        //CreatePDFGenButton(); 
        GeneratePDFAndMsg();
        btnGeneratePDF.Visible = true;

        AddVerticalSpace();
        GenerateLegalNotice();
    }
    catch (Exception ex)
    {
        message.Text = String.Format("Exception occurred: {0}", ex.Message);
    }
}

如果您正在谈论阻止在网络浏览器中提交表单,您应该为此使用客户端代码(即 JavaScript)。即使有一种方法可以在代码隐藏中做到这一点,它也只会被翻译成客户端代码。否则,即使保留了编辑后的值,表单也会提交。

第一Default.aspx来源:

    <script type="text/javascript" language="javascript">
        function validateData() {
            var payment = parseFloat(document.getElementById('boxPaymentAmount').value).toFixed(2);
            var total = parseFloat(document.getElementById('boxGrandTotal').value).toFixed(2);
            if (payment == null) payment = 0;
            if (total == null) total = 0;
            if (payment == total) {
                return true;
            } else {
                alert('Total and Payment Total do not match. Please enter the same amount for both values and try again!');
                return false;
            }
        }
    </script>

    <asp:TextBox ID="boxPaymentAmount" runat="server"></asp:TextBox><br />
    <asp:TextBox ID="boxGrandTotal" runat="server"></asp:TextBox><br />
    <asp:Button ID="btnSave" runat="server" Text="Button" OnClientClick="return validateData();" OnClick="btnSave_Click" />

以及 Default.aspx.cs 的代码:

public partial class Default : System.Web.UI.Page
{

    protected void btnSave_Click(object sender, EventArgs e)
    {
        //TODO: do your stuff here...
    }

}